Hide and show panel in NGUI

I am new to NGUI and unity 3d . I have two panels at the root of ui . it is called firstPanel and secondPanel . secondPanel is deactivated in the scene. I have so many buttons in firstPanel , and one has a play button, i.e. an image button. By clicking on the play button, firstPanel should get hide and secondPanel should show .I add a new Script button to play and write the code in it

 void OnClick(){ GameObject panel2 = GameObject.Find("secondPanel"); NGUITools.SetActive(panel2,true); GameObject panel1 = GameObject.Find("firstPanel"); NGUITools.SetActive(panel1,false); } 

But I get this Error : "NullReferenceException" In what Script of NGUI do I need to edit and how can I do this? help me solve this problem Thanks in advance.

+6
source share
4 answers

If your panels are called Panel1 and Panel2, you will not find them with GameObject.Find ("secondPanel") and GameObject.Find ("firstPanel"). If "Panel1" and "Panel2" are the only name in the game scene (there are no other Panel1 or Panel2), you can try using

 void OnClick(){ GameObject panel2 = GameObject.Find("Panel2"); NGUITools.SetActive(panel2,true); GameObject panel1 = GameObject.Find("Panel1"); NGUITools.SetActive(panel1,false); } 
+8
source

GameObject.Find ("Something") cannot find any disabled game object, so you cannot use this method. You can try adding a reflection to your button code:

 public GameObject pannel1 = null; public GameObject pannel2 = null; 

and set them to the right pane in the scene editor window.

Another way: first you need to keep both of your panels active in your scene, and then add the code to your script button as follows:

 private GameObject panel1 = null; private GameObject panel2 = null; void Start() { panel1 = GameObject.Find("Panel1"); panel2 = GameObject.Find("Panel2"); } void OnClick() { panel2.SetActiveRecursively(true); panel1.SetActiveRecursively(false); } 

The GameObject.Find (line name) function is not very efficient in Unity3D, so do not try to use it in Update () or every time you click a button.

+3
source

I know this thread is outdated, but if someone else has problems calling panels when they are inactive, you can pin your panel and use NGUITools.AddChild to call your panel. It will look something like this.

 public GameObject parent; public GameObject child; void Spawn () { NGUITools.AddChild (parent, child); } 

Assign your UIRoot to the parent (or whatever you want to add to the panel), and assign your panel to a child in the editor, and you're done! I hope this helps someone, this is a common problem when you first work with NGUI.

Happy coding :)

+1
source

You cannot use GameObject.Find () to find a disabled game object, it returns null;

0
source

All Articles