Varaquilex
Varaquilex

Reputation: 3463

Unity3D-C# array initialization and population: Null Reference - Object reference not set

I'm trying to save my game data. At the point of 'copy game data into serializable class objects' I'm having an issue. Here is my code:

public static void Save()
{
    // set save file
    .
    .

    // import game data to serializable class
    PlayerData data = new PlayerData();

    GameObject[] tiles = GameObject.FindGameObjectsWithTag("Tile");
    int i = 0;
    print (data.tiles.Length);  // prints as expected (initialization in constructor)
    foreach(GameObject tile in tiles)
    {
        data.tiles[i].X = tile.GetComponent<TileScript>().X;
        ^^^^^^^^^^^^^^^
        //null reference: object reference not set to an instance of object

        i++;
    }
    .
    .
    .
    print ("Game Saved!");
}

And here is the class I'm trying to save my game data into:

[Serializable]
class PlayerData
{
    public class Building
    {
        public int index;
    }
    public class Tile
    {
        public int X,Y;
        .
        .
    }

    public Tile[] tiles;

    public PlayerData()
    {
        tiles = new Tile[40];

    }
}

I cannot locate the mistake I make. Is there a special case with the [Serializable] class member initialization? Where do I make the mistake and how can I fix it?

Upvotes: 2

Views: 3709

Answers (1)

Chris Sinclair
Chris Sinclair

Reputation: 23208

Each element of tiles is initialized to the default value of Tile. If Tile is a reference-type (i.e., a class rather than a struct), then it will be null. In addition to creating the array, you need to initialize each element to a new Tile object:

public Tile[] tiles;

public PlayerData()
{
    tiles = new Tile[40];
    for (int i = 0; i < tiles.Length; i++)
        tiles[i] = new Tile();
}

When you don't do this and you try to access the data at:

data.tiles[i].X

data.tiles[i] will return null. Attempting to access the X member on the null reference naturally throws your NullReferenceException.

Upvotes: 1

Related Questions