Author Topic: Cannot find NGui element by GameObject.Find  (Read 5893 times)

4everlove

  • Guest
Cannot find NGui element by GameObject.Find
« on: May 24, 2012, 08:27:41 AM »
Hi,

I came across a very strange problem. I add a panel through Editor, with name "DisplayPanel". Then I tried to get a pointer to this game object by GameObject.Find("DisplayPanel"). However, I only got a null pointer. The same thing happens to another panel. It is weird that the third panel, which I instantiated by a prefab, could be retrieved in this way. Any idea about that?

Thanks,
Alan

loopyllama

  • Guest
Re: Cannot find NGui element by GameObject.Find
« Reply #1 on: May 24, 2012, 09:24:32 AM »
This is less of an NGUi thing and more of a Unity thing. GameObject.Find only returns active game objects. If it returns null there are only two possibilities:
  • it is not in your scene (or there is a typo in the string)
  • it is in your scene but the game object is not active.

4everlove

  • Guest
Re: Cannot find NGui element by GameObject.Find
« Reply #2 on: May 24, 2012, 06:22:40 PM »
@loopyllama

Yeah, you're right, I deactivate that element in editor and want to re-activate in the game. Then how can I find such a deactivated item?
« Last Edit: May 24, 2012, 06:37:54 PM by 4everlove »

dlewis

  • Guest
Re: Cannot find NGui element by GameObject.Find
« Reply #3 on: May 24, 2012, 07:27:17 PM »
@loopyllama

Yeah, you're right, I deactivate that element in editor and want to re-activate in the game. Then how can I find such a deactivated item?

The way I go about it is to have one game object with a 'helper' script attached which is just a list of variables. I then find this helper object and can access all the UI elements through there (and enable/disable them as I need).

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: Cannot find NGui element by GameObject.Find
« Reply #4 on: May 24, 2012, 09:37:44 PM »
Directly referencing the script via a public variable on your control script is generally the best way to go. You can drag & drop the value in the inspector, and can easily change it later without having to modify the script. Plus if you rename or move it, it won't mess up your code.

4everlove

  • Guest
Re: Cannot find NGui element by GameObject.Find
« Reply #5 on: May 27, 2012, 11:00:09 AM »
Ya~Thanks for all your kind helps!

Nicki

  • Global Moderator
  • Hero Member
  • *****
  • Thank You
  • -Given: 33
  • -Receive: 141
  • Posts: 1,768
    • View Profile
Re: Cannot find NGui element by GameObject.Find
« Reply #6 on: May 27, 2012, 11:26:06 AM »
Never use find unless you really really have to for some reason.

And when you do, use it once and cache the reference.

And in general, if it's something you always have in the scene, make a direct public reference and drag your thing on that.