Hide Button in unity3d

You can attach this script to your button.

Button buttonToHide;

void Start(){
   buttonToHide = GetComponent<Button>();

   buttonToHide.onClick.AddListener(() => HideButton());
}

void HideButton(){
   buttonToHide.gameObject.setActive(false);
}

Basically what does the code do is, adding the listener event to the button. so everytime you click, it will call HideButton() which hide the button in hierachy.


To Create a UI Button

You can use the Unity's UI System to create buttons. Right click the Hierarchy, click UI, then select Button. A canvas will be created with the button. In the Button's Inspector you will see a small panel on the very bottom that says "On Click()". Click the plus arrow. Attach your script to an empty game object, by right clicking the Hierarchy and clicking "Create Empty". Find your script from your Project folder and drag the script to the empty game object you just created in your Hierarchy. Then click on the Button, that you created inside the canvas, again, and drag the empty game object to the little box that says "None". Click the "No Function" box to reveal a drop down, and find the function that you want to execute when you press the button.

Scripting

You can reference the button you are trying to hide like a GameObject like this:

GameObject button;
void Start() {
    button = GameObject.Find ("Button");
}

In this example, ButtonClicked() is the function that you have selected to execute in the inspector once the button is clicked. You would use the SetActive() method to hide it or make it reappear:

void ButtonClicked() {
    button.SetActive(false);   
}

Unity Manual SetActive()

UI Button


The absolutely simplest you can do is to use the Unity built in functions.

  • Select the button in your Scene/Hierarchy
  • Scroll down to the Button (Script) in the Inspector
  • Click the + button in OnClick
  • Drag the Button game object from Hierarchy into the now created Empty slot "None (Object)"
  • Click the drop down, Select: GameObject.SetActive
  • Don't check the check box
  • Press play and try it

Button in Unity

Tags:

C#

Unity3D