I’m trying to initialize a 2D array and have another GameObject use it. In my case, the 2D array i’ve created is GameObject[,] gameBoard. However, whenever the other class is referencing it, I keep getting a NullReferenceException.
public class GameBoard : MonoBehaviour {
public const int ROWS = 6;
public const int COLUMNS = 5;
private GameObject[,] gameBoard;
public static int numberOfDifferentPieces = 5;
// Use this for initialization
void Awake () {
gameBoard = new GameObject[ROWS, COLUMNS];
}
// Update is called once per frame
void Update () {
// Testing
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log(gameBoard[0, 0].name);
}
}
// Changes the gameBoard array to reflect game piece positions in game
public void setGameBoardPosition(int row, int column, GameObject gamePiece)
{
gameBoard[row, column] = gamePiece;
Debug.Log("Setting X: " + row + " Setting Y: " + column + " with GamePiece: " + gameBoard[row, column].name);
}
The other class:
public class MovePiece : MonoBehaviour {
void OnTriggerEnter(Collider other)
{
string colliderName = other.gameObject.name;
// When a piece collides with a differnt tile on the gamebaord, set its lastPosition to the new tile
// and change the array in GameBoard
if (other.tag == "GameBoard")
{
lastPosition = other.gameObject;
string[] coordinate = colliderName.Split('x');
int row = Int32.Parse(coordinate[0]);
int column = Int32.Parse(coordinate[1]);
this.row = row;
this.column = column;
// Causes NullReferenceException
gameBoard.setGameBoardPosition(row, column, this.gameObject);
}
}
I’ve also tried initializing the 2D array at the beginning of the class like this:
private GameObject[,] gameBoard = new GameObject[ROWS, COLUMNS];
This works and the 2D array is filled with GameObjects properly, but when I try to reference the 2D array in the Update() method of GameBoard (the same class) by doing
// In GameBoard class
void Update () {
if (Input.GetKeyDown(KeyCode.Space))
{
// Causes NullReferenceException
Debug.Log(gameBoard[0, 0].name);
}
}
I get a NullReferenceException, saying that gameBoard[0, 0] is null. This is odd to me because referencing an element within another method seems to return a valid GameObject, seen in this method:
// In GameBoard class
public void setGameBoardPosition(int row, int column, GameObject gamePiece)
{
gameBoard[row, column] = gamePiece;
Debug.Log("Setting X: " + row + " Setting Y: " + column + " with GamePiece: " + gameBoard[row, column].name);
// Prints just fine
}
Am I initializing the 2D array in the wrong place or in the wrong way?