Accessing component of game object in array.

I’m probably doing it wrong.

I want to make an array of gameobjects by tag.
Then iterate through that array and for each gameobject near the one running this script, execute a function or modify a variable of the script attached to that gameobject.

thusly:

var gos : GameObject[];
gos = GameObject.FindGameObjectsWithTag ("TaggedObject");
for (var go in gos)
{
var script = gameObject.GetComponent(script);
script.function(variable);
script.variable += 4;
}

which gives the error:

NullReferenceException: Object reference not set to an instance of an object

Any thoughts?

Thanks in advance.

whenever theres a null reference exception it means something does not exist but your trying to call on it.

I take it the code you posted was just example code. Since you use script in the get component as well as initializing. But basically before calling anything on script you want to check if it exists

if(script){ script.function(variable); script.variable += 4; }

only reason you would not do that if you have some self imposed rule of any game object with given tag will have given component attached. Even then its still a good idea to check for script.

Always double click the console line saying nullreferenceexception which should bring up the text/script editor your using and highlight the problematic line. If its a null reference exception it always means somethings null and your trying to use it as if it exists when it does not. Its not always super obvious as you could have multiple calls in one line. But you should be able to figure out by testing manually with a if(variable)