- Home /
Using an Array to spawn a random object
I am trying to spawn a random gameobject on an empty game object when i push my mouse button. I get the following error.
NullReferenceException: Object reference not set to an instance of an object (wrapper stelemref) object:stelemref (object,intptr,object) RandomPiece.Update () (at Assets/Scripts/RandomPiece.js:17)
I can't figure out what I am doing wrong. Below is my code.
var respawnPrefab : GameObject; var respawnPrefab1 : GameObject; var respawnPrefab2 : GameObject; var respawn : GameObject; var loopHandle : boolean = true;
function Start() { if (respawn==null) respawn = GameObject.FindWithTag ("Respawn"); }
function Update() { var objs : GameObject[];
objs[0] = respawnPrefab; objs[1] = respawnPrefab1; objs[2] = respawnPrefab2;
if (Input.GetKeyDown (KeyCode.Mouse0)) {
Instantiate(objs[(Random.Range(0, objs.Length))], respawn.transform.position, respawn.transform.rotation); } }
Answer by Tourist · Dec 14, 2012 at 10:27 AM
You have a null variable.
Go to the line 17 in your script (because : (at Assets/Scripts/RandomPiece.js:17)) and then check all variables before using them.
Assuming the line 17 is : Instantiate(objs[(Random.Range(0, objs.Length))], respawn.transform.position, respawn.transform.rotation);
then check 'respawnPrefab', 'respawnPrefab1', 'respawnPrefab2' and 'respawn' are not null like this :
var iRandomIndex = Random.Range(0, objs.Length);
if(objs[iRandomIndex] == null)
{
Debug.LogError("The prefab is not referenced at index " + iRandomIndex);
}
else if(respawn == null)
{
Debug.LogError("There is no respawn gameobject in this scene.");
}
else
{
Instantiate(objs[iRandomIndex], respawn.transform.position, respawn.transform.rotation);
}
I think I am declaring items in the array incorrectly but I am so new to program$$anonymous$$g that I can't say where I am wrong. Line 17 is were I am trying to link items in my array to the array I named objs.
Below are lines 16-19 where I am trying to fill my array with game objects.
var objs : GameObject[];
objs[0] = respawnPrefab;
objs[1] = respawnPrefab1;
objs[2] = respawnPrefab2;
Here is a documentation on how to use arrays in javascript : http://docs.unity3d.com/Documentation/ScriptReference/Array.html
Your variable objs is null. var objs = new GameObject[3];
Your answer
Follow this Question
Related Questions
Getting Vector3 from random item in List 1 Answer
How do i prevent an object instantiating another object straight away 2 Answers
How to randomly pick a gameobject except for one gameobject in an array ? 1 Answer
Assign role randomly from array 2 Answers
Array choosing more than one random choice in Start function 0 Answers