- Home /
Cannot add Instaniated gameObjects to a GameObject[] using Javascript. Error: "NullReferenceException: Object reference not set to an instance of an object"
I have a script that is Instantiating gameobjects but when I assign them to a variable I cannot add that gameObject to a GameObject array so I can use it later.
for ( var i = 0; i < amount; i++ ) {
var object_id : int = Random.Range(0,platform_array.length);
var platform_clone = Instantiate(platform_array[ object_id ], Vector3(0, 0, platform_length*platform_count) , Quaternion()); // The Instantiate command takes a GameObject, a Vector3 for position and a Quaternion for rotation.
Debug.Log( platform_clone );
platform_clone_array.Add( platform_clone.gameObject );
platform_count++;
}
I have tried using:
platform_clone_array.Add( platform_clone.gameObject );
platform_clone_array.Add( platform_clone );
platform_clone_array.Push( platform_clone);
platform_clone_array += platform_clone;
platform_clone_array[i] = platform_clone.gameObject;
Which no success. I can Debug.Log it and it appears "brick_checkpoint(Clone) (UnityEngine.GameObject)" exactly as it should and also in the heirachy but just says "Object reference not set to an instance of an object" when I try and add it to the array.
Any help on this would be great, as I am pretty new to Unity but have experience with other code.
I don't see the code where you define platform_clone_array, you need to create this var before using it.
Sorry,
It was defined at the top of my script as
private var platform_clone_array : GameObject[];
but this was actually where the error lied. I will post the answer now.
Answer by Vaughanjb · Apr 09, 2014 at 02:43 PM
This has now been fixed.
I was using
private var platform_clone_array : GameObject[];
Which you cannot add or remove from so instead I am now using
private var platform_clone_array = new Array();
Then to add to the array:
platform_clone_array.push (gameObject);
Answer by thinkwayne · Apr 09, 2014 at 03:27 PM
My Javascript is a little rusty but as KiraSensei said in the comments you need to define your array:
var platform_clone_array = new Array();
//your code
for ( var i = 0; i < amount; i++ ) {
var object_id : int = Random.Range(0,platform_array.length);
var platform_clone = Instantiate(platform_array[ object_id ], Vector3(0, 0, platform_length*platform_count) , Quaternion()); // The Instantiate command takes a GameObject, a Vector3 for position and a Quaternion for rotation.
Debug.Log( platform_clone );
platform_clone_array[i] = platform_clone.gameObject;
platform_count++;
}
Your answer
Follow this Question
Related Questions
Instantiating a random dropped consumable item from many cloned objects 1 Answer
Instantiate without (clone) in JS. 1 Answer
Accessing variable of instantiated prefab inside array in javascript 1 Answer
Following Object can't find newly Instantiated Object (Solved) 1 Answer
How to spawn objects from CSV file 1 Answer