- Home /
"NullReferenceException" Error when trying to count objects with a particular tag using GameObject.FindGameObjectsWithTag function
Hello. I have just started coding in UnityScript roughly a week ago and have no prior coding experience, so don't be surprised if this query seems ignorant.
I want to instruct unity to spawn a number of cubes at unique points on a grid. I don't want two or more cubes to occupy the same space, nor do I want to end up with any less than the my desired number (value of the GlobalVar.numberCubeObstacles variable.)
The countCubes function should be invoked once for every iteration of the while loop, making it possible to derive the number of objects with the "CubeObstacle" tag from the length of the CubeCount variable (an array of references to GameObjects?).This should cause it repeat the instructions as many times as necessary.
When I run the game, the code compiles normally but I get this error:
NullReferenceException: Object reference not set to an instance of an object UnityScript.Lang.Extensions.get_length (System.Array a) Spawn.Start () (at Assets/Evolution Simulation/Scripts/Spawn.js:10)
Here is the relevant code including the CubeCount function:
function Start(){ var cubeCount : GameObject[]; var CollidersCheck; Invoke ("countCubes",0);
while (cubeCount.length<=GlobalVar.numberCubeObstacles){//<< This is line 10
Invoke ("countCubes",0);
var cubePosition = Vector3(Random.Range(-18, 18),0.5,Random.Range(-18, 18));
CollidersCheck = Physics.OverlapSphere (cubePosition,0.5);
if (CollidersCheck.lenght == 0){
//No colliders detected
Instantiate(cubePrefab, cubePosition, Quaternion.identity);
}
}
}
function countCubes(){ cubeCount = GameObject.FindGameObjectsWithTag("CubeObstacle"); }
I did something similar earlier, simply printing the length of an array of game objects with a particular tag to the console and it worked. I'm not sure if the problem is specifically how I'm attempting to use the length of the array or some other mistake.
Answer by Simon Crowe · May 01, 2011 at 06:47 PM
I am fairly certain of what was wrong with my code. Initially, the CubeCount Array would be null due to the lack of any objects in the scene tagged CubeObstacle. This would mean that any attempt to reference it would result in the "NullReferenceException: Object reference not set to an instance of an object" error.
the main issue is that you're calling countCubes a frame later than using it (Invoke with 0 won't call it immediately). use countCubes() ins$$anonymous$$d of invoke and it should fix it