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);
	for(var i = 0; i < 7; i++)
		Instantiate(SortedScards_, transform.position + Vector3(((3*i)-9),-11, -5), transform.rotation);_
  • }*

  • for(i = 7; i < 13; i++)*

  • {*
    Instantiate(SortedScards_, transform.position + Vector3(((3.61i)-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,

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:

Note I’m assuming that you are not allocating space in the RandomizeArray() function.