Historically, I seem to have a lot of problems with arrays. Here’s my current problem… I’m setting up a 2D built-in array of custom objects, and whenever I attempt to access one of the indexes, I get a null reference exception. Here’s my whole code dump. Line 28 is indicative of the problem as trying to view a value in index[0,0] of the array is just erroring out. Any help would be greatly appreciated!
using UnityEngine;
using System.Collections;
public class ArrayController : MonoBehaviour
{
private GridArray p1Grid;
private GridArray p2Grid;
public class GridArray
{
public Cell[,] cells = new Cell[ 6, 12 ];
public class Cell
{
public int cellX = 0;
public int cellY = 0;
public EmailPiece mail = null;
}
}
// Use this for initialization
void Start ()
{
p1Grid = new GridArray();
p2Grid = new GridArray();
print(p1Grid.cells[0,0].cellX);
for( int myY = 0; myY < 12; myY++ )
{
for( int myX = 0; myX < 6; myX++ )
{
// Set up the internal x and y values of the Grid
// I'm not sure this is necessary, but what the hay
p1Grid.cells[ myX, myY ].cellX = myX;
p1Grid.cells[ myX, myY ].cellY = myY;
p2Grid.cells[ myX, myY ].cellX = myX;
p2Grid.cells[ myX, myY ].cellY = myY;
}
}
}
public void SetPiece ( GameObject mail1, GameObject mail2, int player )
{
GridArray playerGrid = new GridArray();
EmailPiece piece1 = (EmailPiece) mail1.GetComponent("EmailPiece");
EmailPiece piece2 = (EmailPiece) mail2.GetComponent("EmailPiece");
if ( player == 1 )
{
playerGrid = p1Grid;
}
else if ( player == 2 )
{
playerGrid = p2Grid;
}
else
{
return;
}
// read the email piece's transform position
int mailX = (int) mail1.transform.position.x + 8;
int mailY = (int) mail1.transform.position.y;
print("mailX: " + mailX + ". mailY: " + mailY);
// find the corresponding index of the player grid
// set the emailpiece of the index
playerGrid.cells[ mailX, mailY ].mail = piece1;
//repeat with second piece
mailX = (int) mail2.transform.position.x;
mailY = (int) mail2.transform.position.y;
playerGrid.cells[ mailX, mailY ].mail = piece2;
}
// Update is called once per frame
void Update () {
}
}