How to find UI in code c# (button, Panel etc)

1.4k views Asked by At

in an empty game object i have a selection Manger script. I'm having some difficulties with finding a panel (called: OpenSelection) I created in Canvas. I would like to find the panel where ever it is in the hierarchy and set enabled to true.

But the code isn't finding the panel. I'm not sure why.


any help would be appreciated

//UI
private GameObject panel;
 
// Start is called before the first frame update
void Start()
{
    panel = GameObject.Find("OpenSelection");
    panel.SetActive(true);
}
2

There are 2 answers

0
Easwar Chinraj On

GameObject.Find() only returns active GameObject. Here you are trying to find the OpenSelection panel which is not active. That's why the Find() is not finding the OpenSelection panel.

1
Lotan On

Generally, Find() is never the best approach for anything.

Try to set a variable reference to your OpenSelection, like you did with your panel, then call this variable.