Trouble with 2D Array for board game

G’day community,

I’m working on a Turn-Based Strategy game in Unity, and am up to the ‘playing field’ itself. I’ve worked with a (pseudo) multidimensional array of integers before for a maze game, but this project calls for a multidimensional array of gameobjects.

I’ve got a 4x4 ‘board’ of cubes, each with the same script attached, that changes their colour when the mouse moves over them.

For the ‘unit’, it has a script that is trying to access a multidimensional array of gameobjects (the ‘board’ cubes) in another script, using an (int) index for both columns and row, to access the GameObject in the next/previous column or row, and change the colour of it.

Here’s what’s on the ‘unit’. It’s supposed to change the colour

function OnMouseUp() {
var colIndex = 0;
var rowIndex = 0;

var targetGameObject : GameObject;

var someScript;
someScript = GetComponent ("fieldScript");

activeUnit = true;

targetGameObject = someScript.grid[rowIndex][colIndex+1];

}

When I try to run this, the last line returns this error:
“Object reference not set to an instance of an object”.

Now, in an empty game object I have the below code, which attempts to create a 2d array of gameobjects. Each game object is assigned to the rows using the property inspector.

var rowA : GameObject[];
var rowB : GameObject[];

var grid = [
    [rowA],
    [rowB]
];

I’ve worked for hours trying to solve this, but nothing seems to work. I’m posting in the hopes somebody might see the cause of my dilema, but please, I need specifics. I’ve read almost every post/thread to be found on everything remotely related to what I’m trying to achieve.

Cheers,

  1. Is “fieldScript” a script found on the same Game Object as this script is attached to?
    If not - it should, since you are looking for a component on the same game object.

  2. Is “fieldScript” the exact name of that script? When possible don’t look for strings. Instead use script types. If you named your script "“fieldScript”, then GetComponent(fieldScript) should work.

  3. Don’t call getcomponent and find functions repeatedly. You should only use them for initialization (or drag the game objects to public variables when possible).

in your case:

var someScript;

function Start()
{
  someScript = GetComponent ("fieldScript");
}

function OnMouseUp() 
{
  var colIndex = 0;
  var rowIndex = 0;

  var targetGameObject : GameObject;

  activeUnit = true;

  targetGameObject = someScript.grid[rowIndex][colIndex+1];

}

It’s far better if you just use an actual multidimensional array:

var board : GameObject[,];

function Start () {
    board = new GameObject[4, 4];
}

This will not work:

var rowA : GameObject[];
var rowB : GameObject[];

var grid = [
    [rowA],
    [rowB]
];

At the time grid is initialised, rowA and rowB are null. The only way I see this working is to set grid in Awake().