[SOLVED] NullReferenceException in a script that calls another object's script variable

Hi. I’m making a tetris-like game and I’m having a NullReferenceException I don’t know how to solve. Here’s the structure more or less:

-GameObject Spawner

-GameObject Piece

Spawner has a script that controls the game status, and everytime a piece touches ground, a matrix named “gameStatus” is updated with the piece’s column, row and some variables.

I’d like to save the whole piece gameObject in the “gameStatus” matrix, so instead of saving all the piece’s variables in the array, I can just get them from the “piece” field.

I have this struct:

public struct gridGap {
	public bool empty;
	
	// these are my current variables, that I want to 
	// avoid saving and just save the piece
	public int id;
	public int hits;
	public int number;
	public string name;
	public float scale;
	public int col;
	public int row;
	
	public GameObject piece;
}

Now, when a piece touches the ground, I can initialize the “piece” element like this:

	public void updateGameStatus ( float scale, int row, int col, int hits, int number, int id, GameObject piece, string name ) {
		if (row > -1) {
			gameStatus[row, col].name = name;
			gameStatus[row, col].number = number;
			gameStatus[row, col].hits = hits;
			gameStatus[row, col].empty = false;
			gameStatus[row, col].id = id;
			gameStatus[row, col].scale = scale;
			gameStatus[row, col].piece = piece;
		}

However, later in the code, if I want to print a piece’s gameObject script variable like this:

				debugMessage = gameStatus[i, j].number + ", " + 
					gameStatus[i, j].piece + ", " + 
					gameStatus[i, j].piece.GetComponent<PieceManager>().hits + ", " + // this line throws a NullReferenceError
					Debug.Log(debugMessage);

I get a NullReferenceException (“NullReferenceException: Object reference not set to an instance of an object”). Even if I just try to print “gameStatus[i, j].piece.GetComponent()” I get that error.

I’m new to Unity and don’t quite understand why I can access the “piece” gameObject but not its attached script to print some variables. Could you please let me know how to properly do this?

Thanks in advance :slight_smile:

(I hate it when I find the solution ONLY shortly after I decide to ask for help…):

It was really easy: the whole gameStatus array’s “piece” fields start as null objects. Thus, when I go through the whole array, when I try to print the script for a piece and that position is empty, I of course get that null alert.

Sorry!