- Home /
show hide button in unity using c#
I have 15 buttons on my screen at onClick event am fetching the button and hiding that button using
EventSystem.current.currentSelectedGameObject.SetActive(false); now at the end i have to show buttons again so i am using
for (int i = 0; i < 15; i++)
{
tag1 = "Button" + (i + 1);
GameObject.FindGameObjectWithTag(tag1).SetActive(true);
Debug.Log("done");
}
Loop is giving error becuase it is not able to find object which has been hidden or setActive(false) from other references unity forum i see same solution by i don't know why it is not working in my case any help will be appreciated Thanks
Answer by dacarrera · Nov 25, 2016 at 09:50 AM
I think this could be simplified. In your hierarchy you can make an empty button manager and make all of your buttons children of it. Then just use GameObject.SetActive(true) to have them appear again. This would work well if you wanted to work with all the buttons at once.
However, if you're looking at making different buttons appear/disappear at different times, you should make an empty __Manager and set each button as a GameObject in a script to manage them.
// Your buttons
public GameObject button1;
public GameObject button2;
public GameObject button3;
// function to enable
public void enableButton(onButton){
onButton.SetActive(true);
}
// function to disable
public void disableButton(offButton){
offButton.SetAdtive(false);
}
You can add the public functions to an on/off button.
thanks @dacarrera your answer is right,just we have save these object references before hiding the object
Answer by Dibbie · Nov 25, 2016 at 09:46 AM
What you could do, is put all your buttons under one gameObject you wont hide, just a simple transform, and child all your buttons to it - since its a UI, use a "Panel", and turn off the Image component of that panel so it acts like just a parent or "holder"... Then in your script, you can find that panel object instead, and loop through each of the children.
for (int i = 0; i < GameObject.Find("PanelWithButtons").transform.childCount; i++){
GameObject.Find("PanelWithButtons").transform.getChild(i).gameObject.SetActive(true);
}
General idea, untested code.
Well the name "PanelWithButtons", is whatever name you gave the panel gameobject in the hierarchy, and it could also be GetChild, ins$$anonymous$$d of getChild as well.
Answer by Denscrivent · Dec 01, 2016 at 08:21 AM
You can put the same tag names to the buttons and you just do this code GameObject[] buttons = GameObject.FindGameObjectsWithTag("Buttons");
foreach(GameObject button in buttons){
button.SetActive(False);
}