I’ve been scouring the forums for more clues as to the syntax for accessing a Component within a GameObject (in an Array). I’m simply trying to create a few GUIText objects in the corner of the screen to provide debug feedback. Below is the code in Start().
Note “debugText” is simply a GUIText Prefab in my Project.
for (int i = 0; i < max; i++)
{
GameObject go = textList[i] as GameObject;
go = Instantiate(debugText) as GameObject;
}
This works fine, but in my Update() I have the following (which compiles, but gives me a Null Reference):
GameObject go = textList[0] as GameObject;
go.guiText.text = "myString";
This works when the object is instantiated, but not in the Update(). I know I’m not pointing to it correctly. Any clue on the correct syntax?
You’re assigning the instantiated object to “go”, but you never assign it back to the array, so the array’s slots are pointing to nothing useful. set textList = go; after you assign go to the instantiated object in the initialization loop.
Ahh!!! That makes sense. I knew I was missing something.
Thanks much-
One more quick question-
Why, when I do calls to the GameObject in the array, do I have to create a local variable converting it into a GameObject? (C#)
They were GameObjects types when they went in, but only considered Objects now.
GameObject go = textList[0] as GameObject;
go.guiText.text = "myString";
How is textList declared? If the array is declared as GameObject[ ] you should be able to access GameObject member variables directly from the array.
Also, in your loop you shouldn’t need the local variable either. This:
for (int i = 0; i < max; i++)
{
textList[i] = (GameObject)Instantiate(debugText);
}
should be sufficient.
Wow- that’s much better. I knew there had to be a simpler way to access the types. Thanks!!
What’s the procedure for adding to that GameObject[ ] array? It doesn’t have a .Add function as I would normally use in a List or Array…
Nevermind. Reading similar posts, I just define the length of it in the constructor/Start().
I suppose to fill it with objects already instantiated, I’d just leave that undefined, and then do GameObject.Find… right?
Exactly! Though GameObject.Find can be slow, so if you can do that part in Start() or Awake() as well you’ll avoid potential hiccups while the game is running.
Great- thanks for the help!
I’ll give it a try.