Remove button in runtime

I have a instance of a button that I want removed. For that , when I click on one of the buttons, it sets himself as the Button current_button variable. I want to remove the current_button, but I have tried different things with no luck so far.

SetActive with current_button.getComponent().SetActive(false);

current_button.enabled = false;


And a few other methods. Could anyone point me how I could achieve this? Thanks for the help.

Your approaches only destroy the button component. A button usually has a graphics target (mostly an image).
If you only destroy the button component, the graphics target will remain on the object.

Either destroy both, or just the complete button’s GameObject:


From my experience the best way to delete a UI button at runtime, or any UI element, is to do the following with the UI element; make it a child of a GameObject and do away with the GameObject, or hide it.

   /*Lets say we generated UI buttons at runtime and named them "1","2, and so forth.
 You can do this easily when you instantiate the UI element/button with the following code

(variable name for the UI element).name=i.ToString();

Let's say our code kept track of an int we named 'i' and every time i was used to create a variable
 name the next line of code incremented i by 1. We made each button created at runtime a child of an empty GameObject whose sole purpose is to nicely store our buttons in the Editor Hierarchy. The variable name in our code referring to this GameObject is "buttonHolder"

  Now when a certain condition is met we want to remove a specific UI button.
   Let's say the UI button we named "3".
   We need to locate it first in the code in order to either hide it or remove it.*/
  void DestroyUI_Stuff(string buttonName){ 
  //create a GameObject at runtime in code and give it a name. 
  //If we see it in the editor during testing/play mode something went wrong...
  GameObject noMore = new GameObject("IShouldNotExist!");
  foreach (Transform child in buttonHolder) //even Button UI elements have a transform 
                  if ( == buttonName)
                      Destroy(noMore); //destroy the button (evil laugh) 
  //noMore.SetActive(false);  <--this code will turn it off instead of destroying it.

Running this method/function looks like this:


To you get a UI component, import to your C# script the UnityEngine.UI.

using UnityEngine.UI;

Then you can get the Component reference to this in your code.


And Destroy this


But if you trying remove the object with a Button Component, you just need Destroy the GameObject.