- Home /
NullReferenceException with object array
Dear Unity supporters,
I have an array of gameobjects and i want just 14 of them stored in another array. But I have already tried hours and cant get the job done.
Here is my example code:
pragma strict
import System.Linq;
public var Cards : GameObject[];
private var Scards : GameObject[];
private var RandomScards : GameObject[];
private var SortedScards : GameObject[];
function Awake () {
Scards = RandomizeArray(Cards);
for(var k = 0; k < 13; k++)
{
RandomScards[k] = Scards[k]; //This doesnt work! this code is my problem
}
var SortedScards = RandomScards.OrderBy(function(go) go.name).ToList();
for(var i = 0; i < 7; i++)
{
Instantiate(SortedScards[i], transform.position + Vector3(((3*i)-9),-11, -5), transform.rotation);
}
for(i = 7; i < 13; i++)
{
Instantiate(SortedScards[i], transform.position + Vector3(((3.61*i)-34.3),-16, -5), transform.rotation);
}
}
I get this error when I try to start the game: NullReferenceException: Object reference not set to an instance of an object (wrapper stelemref) object:stelemref (object,intptr,object)
Can somebody please explain what I am doing wrong and how I can fix it. (Sorry for my poor english) With kind regards, Speed
Answer by robertbu · Oct 11, 2014 at 06:53 AM
You are not initializing your arrays. You declare a variable, but you are not allocating space and assign the reference to your variables. If all the arrays marked private are either 1) of a know size, or 2) you can define a reasonable maximum, then you can do:
private var Scards : GameObject[] = new GameObject[8];
If you cannot define a size but need them to grow, you will need to use a data structure other than Unity's built in arrays. The typical data structure in this situation is a generic List. More information on other collections types:
http://wiki.unity3d.com/index.php?title=Which_Kind_Of_Array_Or_Collection_Should_I_Use%3F
Note I'm assuming that you are not allocating space in the RandomizeArray() function.
Thank you verry much Robertbu, it has solved my problem!
Have a nice day
Your answer
Follow this Question
Related Questions
Using an object pool with Javascript. 1 Answer
Load Prefabs in Array with Javascript 1 Answer
How can I instantiate a GameObject directly into an array? 3 Answers
Array problem -3 Answers