NullReferenceException on Public Variable only Outside the Class

It doesn’t really make sense to me that inside the class I have set up the variable called allTiles and gave it multiple values but every time i refer to allTiles outside the class i get a NullReference Error as if all the values are there but are set to null D:

The TileHill is a sub-class of Tile and they both have constructors to set numUnits to 0.

public class TileManager : MonoBehaviour {
	
	public const int TILES_X = 12;
	public const int TILES_Y = 6;
	
	public Texture[] terran = new Texture[2];

	public Tile[,] allTiles = new Tile[TILES_X, TILES_Y];

	void Start () {
		for(int i = 0; i < TILES_Y; i++) {
			for(int j = 0; j < TILES_X; j++) {
				if(Random.Range(0.0f, 1.0f) < 0.5f){
					allTiles[j, i] = new Tile();
				}
				else{
					allTiles[j, i] = new TileHill();
				}
			}
		}
	}
}

public class GameScreen : MonoBehaviour {
	
	TileManager tileManager = new TileManager();
	GameManager gameManager = new GameManager();

	void OnGUI () {
		int BTN_SIZE_X = Screen.width/12;
		int BTN_SIZE_Y = Screen.height/8;

		float groupSizeX = BTN_SIZE_X * TileManager.TILES_X;
		float groupSizeY = BTN_SIZE_Y * TileManager.TILES_Y;

		GUI.BeginGroup(new Rect((Screen.width - groupSizeX) / 2f, 0, groupSizeX, groupSizeY));

		for(int i = 0; i < TileManager.TILES_X; i++) {
			for(int j = 0; j < TileManager.TILES_Y; j++) {
				if(GUI.Button(new Rect(BTN_SIZE_X*i, BTN_SIZE_Y*j, BTN_SIZE_X, BTN_SIZE_Y), "" + tileManager.allTiles[0,0].numUnits)){
					gameManager.setSelection(i, j);
				}
			}
		}

		GUI.EndGroup();
	}
}

First of all, sinse TileManager is a MonoBehaviour, you can’t instantiate it using the ‘new’ keyword (Unity should display a warning in the console notifying you about this I believe)

That leaves me to what is most likely your problem, GameScreen.tileManager is not set. sinse this is a private variable and you can’t instantiate it using the new keyword, so tileManager is null :wink: Simplest thing would be to make it a public variable and assign it in the inspector. Or use another way to find the TileManager and assign it in the Awake/Start (GameObject.Find/GetComponent/etc.)

Same thing counts for the GameScreen.gameManager if this is a MonoBehaviour btw.

As I mentioned in the comment, Unity prevents the GameScreen class from creating an instance of the TileManager class.

It would also happen if your GameManager class is also derived from MonoBehaviour class.

Thus the tileManager references will remain null.