My first question here. I'll try to be clear :) Is there a way to get the value of a variable in a script, on a GameObject in an array? I have an array of GameObjects, on which each of them has the same script attached (ExampleScript). In the ExampleScript there is a int variable (exampleInt), that is generated within the script. I want to print out each of the exampleInt values, for each of the GameObjects. My code (which results in a NullReferenceException) is:
public GameObject[] exampleGo; //all the GameObjects are manually added in Inspector
private void Start()
{
foreach (GameObject go in exampleGo)
{
Debug.Log(go.GetComponent<ExampleScript>().exampleInt);
}
}
Can you help me Stack Overflow, you are my only hope?
I've tried delaying the script, in case something hasn't been generated when I run the code above.
I'm just barely understanding NullReferenceExceptions, but this one is trickier than my earlier encounters with it for some reason.
exampleGoarray is null (unlikely, if you set it in the inspector), your array contains anullgameobject (labeled as "None" or "Missing" in the inspector), or one of the objects you put in the array don't have anExampleScript.GetComponent<ExampleScript>()by changingpublic GameObject[] exampleGo;topublic ExampleScript[] exampleGo;. Then, you can loop over the instances of these components directly, instead of looping over the gameobjects attached to them.GetComponent<ExampleScript>()is likely results in null reference, althugh weird,I would have think that implementation of such thing would use a null-object pattern.