I created a GameObject array.
public GameObject[ ] gameArray = new GameObject[10];
I created Canvas Buttons.
I click and drag the buttons into the gameArray[ ]
I am able to change the color of each button.
I am trying to change the Text in each button, but I can’t figure out how to do this.
I have tried several was but nothing works.
I get the error:
Object reference not set to an instance of an object.
I figured it out. Text is it’s own GameObject.
I just needed to create another GameObject array and add the Text GameObjects ot that.
Then I was able to change the text.
bokText[ ] is the GameObject array.
Then
bokText[setBox].GetComponent().text = “RED”;
Works!
Which object reference isn’t set to an instance of an object? I’m guessing from the last reply that you’re trying to access a script in a GameObject from an empty array slot. If you’re filling the array from the Inspector, you don’t need to initialize it from your script, it’ll do that with background magic since it’s an inspector-accessible field. Just remove the “new GameObject[10];”, add only as many slots as you actually need in the inspector, fill them, and try again.
If you’re still having problems after that, repost your code (in [code ][/code ] tags) along with the complete error (screenshot of the error works too).
To be honest I would actually use an array of Buttons instead of GameObjects. Unless you have some edge case where GameObjects are preferable, in which case you’ll want to use null reference checking.
Yeah, it actually took me a few weeks after starting with Unity awhile back to figure out that I could specify component types, and then proceed to drag GameObjects into the slot in the inspector and it would only grab the component reference from them. It’s like magic.
This is yet another way in which Transforms and Renderers having “shortcut members” was a bad idea IMO, because despite seeing hundreds of examples of people dragging in Transforms in exactly that way, it didn’t occur to me for quite awhile that Transforms were “just another component” and you could do that with anything.