- Home /
2d array: finding out if an item is null?!?
My inventory script is structured as follows: A 2d array of GameObjects
var InvMain : GameObject[ , ] = new GameObject[12,4];
first integer describes the inventory slot (12 total) and the second int describes the items in that slot, so stacked items can be stored. So far, so good.
Now, to display my stored inventory items, I use the simple code
function OnGUI()
{
for (var x = 0; x < InvMain.Length; x ++)
{
if(InvMain[x,0] != null)//always show the first item of a stack of items
{
//icon positions and sizes are stored in seperate lists that are not important for this question
//the coordinates here are just a placeholder
GUI.DrawTexture (Rect(100 + x * 20, 100 + x * 20, 20, 20), InvMain[x,0].GetComponent(EL_Item).Icon);
}
}
}
The problem here is the if(InvMain[x,0] != null) part, if my 2d array's second dimension is only size 1 (GameObject[12,1]), then it all works fine. If it's bigger than 1 however, then I get an "ArgumentOutOfRangeException: Argument is out of range." error.
It seems as even though I specifically check if the item at position [x,1], [x,2] and so on are not null, it still tries to access it and draw icon graphics etc.
How does one check if an item at a specific positions inside a 2d array is null? Also, my 2d array doesn't show up in the inspector :(
Answer by Cherno · Sep 23, 2013 at 07:36 PM
I found out what the issue here was myself:
this code:
for (var x = 0; x < InvMain.Length; x ++)
, specifically the InvMain.Length part, give a length of 48 (12 x 4). To get the length of the first dimension, it has to be InvMain.GetLength(0):
for (var x = 0; x < InvMain.GetLength(0); x ++)
This will give you the length of the first dimension (the "rows" of the array). For the second dimension (the "columns"), use InvMain.GetLength(1).
Your answer
Follow this Question
Related Questions
Creating an inventory/weapon array and ability to scroll through it 1 Answer
JavaScript Grid Array Size 0 Answers
Is this considered bad coding 1 Answer
Array index is out of range? 1 Answer
Saving Transform Array 0 Answers