- Home /
Why is this not working?
I'm trying to find all the gameobjects with a specific tag and then change a variable in the components of them but this code is saying null reference at the last line. This is supposed to happen after a trigger. The trigger works because the debug is showing its working but the for statement isn't.
Code:
private GameObject[] blocks;
void OnTriggerEnter(Collider col)
{
if(col.tag == "Player")
{
Debug.Log("Works");
blocks = GameObject.FindObjectsWithTag("terrain");
for(int t = 0 < blocks.Length; t++)
{
//This is where the null reference is coming from.
blocks[t].GetComponent<TerrainBlock>().stop = true;
}
}
}
try to print blocks.Length before the for loop to see if you have any. then you have to be sure that your terrain object is a child and have TerrainBlock component attached.
maybe your tag is Upper-Case or something like this. try with only one object that has tag , so can help to solve it...
also line 14 should only have one = (setting a value to equal something, not using an operator) :
blocks[t].GetComponent<TerrainBlock>().stop = true;
and as moghes said, either the object(s) tagged terrain doesn't have the component TerrainBlock, or stop is not a (public) variable of the component.
Based on the first tag ("Player") it seems you're starting your tags with an upper-case letter. Change "terrain" to "Terrain" and try it out
Oh yes sorry It is onlu one =. force of habit made me type ==...