- Home /
create an array of unknown size in a loop
Hi there, I have a loop that fills an array. basically I go through a simple puzzle game level, look for vacant locations and write the location in the list. Later, I pick a random location from the list and do something.
var availableLocations=new Block[xwidth*ywidth];
var internalLoop:int=0;
//x axis loop
for(x=1;x<ywidth-1;x++)
{
//y axis loop
for(y=1;y<ywidth-1;y++)
{
if(levelArray[x,y].type==BlockType.Nothing) //check if there is nothing yet at the location
{
availableLocations[internalLoop]=levelArray[x,y]; //add the location to the list of available locations
internalLoop+=1;
}
}
}
//create a goal block at one of the available locations
var r=Mathf.Floor(Random.value*availableLocations.length);
print("trying to create a gloal block at location"+r);
var goalBlock=availableLocations[r];
goalBlock.type=BlockType.Goal;
goalBlock.color=levelColors[currentGoalBlockColor];
the problem is, that my array is too one and I sometimes get nullReferenceExceptions because I tried to access an object that wasn't written in my array because the array is as big as the whole level, but the amount of vacant locations is only a part of the level.
note: at the last line I use a method of the Block at the picked location in the array. I was thinking about using the native javascript array, but the problem is that, if I do something like Array[].method with it, I get an error because the items are generic objects instead of the classed i've used so I can't use methods (at least as far as I now I can't as I tried)
How can I make availableLocations[] be only as big as internalLoop gets during the loop?
thanks in advance!
Simply use a "Javascript Array" (read up on them) ... but moreover, don't use those!
They are out of date. Simply use the LIst form. ( import System.Collections.Generic; private var rr : List.; etc etc )
See here for a massive incidental discussion:
http://answers.unity3d.com/questions/198318/javascript-array-use-with-a-struct-.html
Answer by Berenger · Jan 20, 2012 at 08:09 PM
Have you tried ArrayLists ? I'm not sure of the name in javascript, but it's probably what you need.
Your answer
![](https://koobas.hobune.stream/wayback/20220613063223im_/https://answers.unity.com/themes/thub/images/avi.jpg)