FrgMan
1
Hi I’m working with a list and I see a very strange behavior.
my code is as follows
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Main : MonoBehaviour {
private List<GameObject> boardInstance = new List<GameObject>();
//.................another code
public void CreateBoard(){
//size=4;
level=1;
lives=4;
time=1f;
dif=4;
shfTimes = (size * size) * 50;
centerCorr = (mosaicSize * size)/2;
Xpos = 0 - centerCorr;
Ypos = 0 - centerCorr;
ArrayList grid
= (ArrayList)this.CreateGrid();
grid = (ArrayList)this.shuffle (grid);
board = grid;
spawnSpot.Set (Xpos, Ypos, 0);
for (int i=0; i<size*size; i++) {
currX++;
if(currX < size){
spawnSpot.Set (Xpos, Ypos, 0);
GameObject mosaicSpawn = (GameObject)Instantiate(mosaic, spawnSpot, transform.rotation);
//Here is the add
this.boardInstance.Add(mosaicSpawn);
showMosaicProp(mosaicSpawn);
Xpos = Xpos + mosaicSize;
}
else{
currX=0;
Xpos = 0 - centerCorr;
Ypos=Ypos+mosaicSize;
spawnSpot.Set (Xpos, Ypos, 0);
GameObject mosaicSpawn = (GameObject)Instantiate(mosaic, spawnSpot, transform.rotation);
this.boardInstance.Add(mosaicSpawn);//and here
Xpos = Xpos + mosaicSize;
}
}
Xpos = Xpos + mosaicSize;
spawnSpot.Set (Xpos, Ypos, 0);
}
As seen in the capture, during the add to the list, generates null objects. in the following iterations “fill” empty spaces,
then created more nulls objects in the list (apparently in power of 2).
I’m sure there is some problem in my handling of the list.
Thank you very much for any help
That’s the correct behaviour.
Whenever the capacity of a list is exhausted, the runtime must shift the list in memory to a new larger location. Moving this memory around is a performance drain. To prevent this happening at too high a frequency, whenever the list is moved, extra slots are added to the underlying array. This is all done automatically for you.
If you know in advance what capacity you need, you can specify it in the constructor.
You can get all the gruesome details on the MSDN
FrgMan
3
Now I understand, thank you.