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
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With