variable value becomes null unity

1.3k Views Asked by At

Member of a MonoBehaviour class loses its value. Here is my code to explain.

I have a class to store data:

public class Tile
{
    public string name;
    public string id;
}

There is a second class where I am using the Tile class:

public class TilesManager : MonoBehaviour
{
    private List<Tile> tiles;

    public void Awake()
    {
        tiles = new List<Tile>()
        {
            new Tile() { name="A", id="A" },
            new Tile() { name="B", id="B" },
            new Tile() { name="C", id="C" },
        };

        // here i set break point and the tiles has value and contains 3 items
    }

    public Tile GetTileAtIndex(int index)
    {
        if(index < 0) index = 0;
        if(index > 2) index = 2;

        // here i set break point the tiles value is null !
        return tiles[index];
    }
}

I call "GetTileAtIndex" method from another script. and it give me null reference exception at line "return tiles[index];".

1

There are 1 best solutions below

1
On

tiles is visibly null until you cal Awake() method. Call that first to instantiate tiles.