- Home /
Unity Object Array C#
Hi there, Im trying to populate an object array in unity using C#, i declare the array like this:
Card[][] aCardGrid;
When I try to assign the card object to the array
aCardGrid[i][j] = new Card();
I get this error:
NullReferenceException: Object reference not set to an instance of an object GameScript.Start () (at Assets/Scripts/GameScript.cs:29)
I tested the creation of the object and it's working fine, just get this error when i try to put it inside the array...
Anyone?
Answer by Mike 3 · Nov 03, 2010 at 08:45 PM
Do you ever instantiate the array? That part of the code is missing
If not:
aCardGrid = new Card[xSize][ySize];
Edit just for sanity's sake:
You can also use a multidimensional array instead:
Card[,] aCardGrid;
aCardGrid = new Card[xSize, ySize];
You won't need to populate the jagged array yourself with inner arrays, and it's guaranteed to be a fixed size in each direction
Do remember that when filling a multidimensional array you will need to use a nested for loop or similar construction. There is no operator specifically for filling 3D or higher arrays Proclyon 0 secs ago
Answer by Proclyon · Nov 03, 2010 at 08:57 PM
This code segment gives me the error Invalid rank specifier: expected ',' or ']' \Program.cs ConsoleApplication4
Adding this answer to support the reminder to fill the 3D array with nested for
using System; using System.Collections.Generic; using System.Linq; using System.Text;
namespace ConsoleApplication4 { class Program { static void Main(string[] args) { Foo f = new Foo();
Foo[][] myArray = new Foo[2][3];
}
}
class Foo
{
public int x;
public Foo()
{
x = 1;
}
}
}