Making an Array of Spawnpoints...

Looking to make a working Array of Game Objects that can be used for spawn locations. I made an Array but I’m getting a error:

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

Which when clicked tell me that there is something wrong with this line of code:

instance = Instantiate(game_cube, arr[randomPick].position, arr[randomPick].rotation);

Here is my script:

private var arr : Array;

var game_cube : Rigidbody;
var cube_count = 0;
var walker0 : GameObject;
var walker1 : GameObject;
var walker2 : GameObject;


function Start () {
	arr = new Array[3];
		arr.Push(walker0);
		arr.Push(walker1);
		arr.Push(walker2);
}
InvokeRepeating("LaunchProjectile", 2, 3);
function Update() {
	if (cube_count>= 10) {
		CancelInvoke();
	}

}

function LaunchProjectile () {
	var randomPick : int = Random.Range(0,2);
		
	instance = Instantiate(game_cube, arr[randomPick].position, arr[randomPick].rotation);
	instance.velocity = Vector3.zero;
	cube_count = cube_count +1;

}

Yes I think the answer is on the original thread. You needed Start or Awake to get it going. It should have given you compile errors.

1 Answer

1

You’ve pushed GameObjects in your array, but you’re trying to read position and rotation, which are properties of Transform, not GameObject. You can change the walker types to Transform (the Inspector will store the correct type). Maybe you need also assign the array element to a Transform variable prior to use it:

    var sPoint: Transform = arr[randomPick];
    instance = Instantiate(game_cube, sPoint.position, sPoint.rotation);
    ...

Make sure that the 3 walker variables and the game_cube are not empty, or this error will haunt you again.

Reading your question again, I noticed that you're creating the array arr with 3 elements, but when you use arr.Push the new element is added to the array, so you end with 6 elements - and the first 3 are empty. Change the first line of Start to: <pre> function Start(){ arr = new Array(); // create an empty array ... </pre>