Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide Button in unity3d [closed]

Tags:

c#

unity3d

I'm a begginer in unity3d and I work on a simple game , there are some buttons and I want to hide them when I click on one of them. Can anyone help me to do that in C# code? Thanks

like image 612
Ritta.. Avatar asked Apr 13 '16 23:04

Ritta..


2 Answers

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

like image 69
Aaron Ge Avatar answered Sep 27 '22 22:09

Aaron Ge


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.

like image 34
Tengku Fathullah Avatar answered Sep 27 '22 21:09

Tengku Fathullah