user7183273
user7183273

Reputation:

Unity 5 2DArray, Object pooling

Im trying to make a object pooling system for my WaveSpawner.

This is what I got (objectPool is a 2D array):

objectPool = new GameObject[wave.Length,0];

//set columns
for(int i = 0;i< objectPool.Length;i++)
{
    objectPool = new GameObject[i,wave[i].numberToSpawn]; //set row for ech column
}


for (int p = 0; p < wave.Length; p++)
{
    for(int i = 0;i<wave[p].numberToSpawn;i++)
    {
        GameObject gbj = Instantiate(wave[p].spawnObject);
        gbj.transform.position = RandomizePositions();
        gbj.SetActive(false);
        objectPool[p,i]= gbj; //fill 2D array
    }
}

Thats the Error I got;

Array index is out of range.

Upvotes: 0

Views: 158

Answers (2)

Toan Tran
Toan Tran

Reputation: 11

objectPool = new GameObject[wave.Length,0];

Second dimension has size 0

for(int i = 0;i< objectPool.Length;i++)

Length return the size of all dimension, use array.GetLength();

You should read how to use 2d dimension array

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays

Upvotes: 1

Daahrien
Daahrien

Reputation: 10320

objectPool = new GameObject[wave.Length,0];

You're creating the array with a size of 0 in the second dimension.

Upvotes: 2

Related Questions