- Home /
Javascript 2D arrays: null values and slicing
Been banging my ahead against JS 2D arrays for a day now. Every answer I look up seems to just lead to another error in a cyclical mess.
I just want a 2D int array initialized to 0. The below gives me an error: "NullReferenceException: A null value was found where an object instance was required" on houseGrid[x,z] = 0;. I've had slicing errors with various other attempts. I'm at my wits end. Help would be greatly appreciated!
#pragma strict
var floor : Transform;
var wall : Transform;
var houseSize : int = 50;
var minRoomSize : int = 5;
var maxRoomSize : int = 15;
function Start () {
var x : int = 0;
var z : int = 0;
var i : int = 0;
var houseGrid : int[,];
houseGrid = new int[houseSize,houseSize];
for(z=0; z<houseSize; z++){
for(x=0; x<houseSize; x++){
houseGrid[x,z] = 0;
}
}
}
That gives a slicing error as well as "Array houseGrid is rank '2', not rank '1'" error for the houseGrid[x,z] = 0 line.
I tempted to say I've read every relevant answer on here. No dice. :< I'm sure I'm just missing something silly.
Answer by Eric5h5 · Sep 19, 2012 at 03:50 PM
The code you posted here compiles and runs without errors. However, as to this:
> I just want a 2D int array initialized to 0.
All you need is:
function Start () {
var houseGrid = new int[houseSize, houseSize];
}
An int can't be null, so an int[,] array always has every entry initialized to 0.
Oh for fuck's sake... I think I had it correct at some point but didn't hit play again to clear the error. (Still new to Unity, not used to the clear on play vs on change errors)
Thanks for pointing out the initialization thing!
There's a clear button in the console, so you don't need to hit play to clear errors.
Your answer
Follow this Question
Related Questions
Javascript 2d array Help 0 Answers
Public 2D array, accessed through the editor ?? 3 Answers
Find colliders after collision? 2 Answers
Problem removing items from array 2 Answers
List problem? 2 Answers