checking for null not working

So I have a 2d tile map which I set in the SpawnTiles() function and use in the DrawTiles() function, the problem is that it throws a NullReferenceException when checking for null, when it should be set to null. Also, I need the array to be set in the SpawnTiles() function, and the array is used in both functions in other code that isn’t any cause for the eror to occur. The SpawnTiles() function also needs to not necissarely be able to be called before the DrawTiles() function, that’s why I need to check if null, so that when it is null, I can call the SpawnTiles() function.

GameObject[,] tileMap;

public void SpawnTiles ()
    tileMap = new GameObject[mapWidth,mapHeight];

public void DrawTiles ()
    if (tileMap[x,y] != null)  // this is where the NullReferenceException is thrown


You’re checking if the item at xy is null, and not if the tilemap array itself is null. It’s not like the item at some index doesn’t exist - your code would handle that - the problem is that the grid itself doesn’t exist.

Luckily it is a simple enough fix:

if (tileMap == null) { SpawnTiles(); }

if (tileMap[x, y] != null)  

Hope this helps :slight_smile: