- Home /
Can not store objects in array
public Transform wisp; GameObject[] wisps; int counter=0; float countdown= 5;
void Update ()
{
if(countdown < Time.time)
{
countdown = Time.time +5F;
wisps[counter]=Instantiate(wisp, new Vector3(Random.Range(40,400),10,Random.Range(40,400)),Quaternion.identity)as GameObject;
counter++;
}
I'm checking and checking again, I'm new to unity so if you can help me, that would be great.
For a reason I could not figured out, I can't store "wisp" objects into wisps array.
Thanks
FYI, it's best to learn to use List - search on here for 100s of discussions about it
Answer by robertbu · Apr 03, 2013 at 08:41 AM
When posting these kinds of questions, it is helpful to include the actual error, and to comment the code you post on the line that gets the error.
The likely issue above is that you did not create space for the array. You you are likely getting a null reference exception. Change your wisps declaration to something like:
GameObject[] wisps = new GameObject[10];
I proposed to use a Generic List if he does not know the exact size he is going to have.
Answer by EliteMossy · Apr 03, 2013 at 08:43 AM
I would recommend using a Generic List instead of an array, as an array is a fixed size, and should only be used if you know exactly how much you are putting into it. Now with the Generic List it keeps track of the size and adjusts it as it's needed.
using System.Collections.Generic;
public Transform wisp;
List<GameObject> wisps;
float countdown= 5;
void Update ()
{
if(countdown < Time.time)
{
countdown = Time.time +5F;
GameObject go = Instantiate(wisp, new Vector3(Random.Range(40,400),10,Random.Range(40,400)),Quaternion.identity)as GameObject;
wisps.Add(go);
}
}
Your answer
Follow this Question
Related Questions
Problem With Enemy AI 0 Answers
My monster only choose one Target 2 Answers
Make Deaths end game 1 Answer
Vehicle help 1 Answer
if statement error 1 Answer