Index Out of Bounds Exception

Hello, I noticed that if all of the Objects in the Pool are active in the hierarchy at once, (before the first enemy has Deactivated itself though death or reaching the end of the path) I get an Index out of Bounds exception, and the spawning cycles breaks.
I have fixed this in my code, by changing the “while(true)” loop to a Boolean “while(spawning)”, that I can toggle with the press of the space bar… this essentially just resets the coroutine so it will begin again. However, I have tried to figure out a solution, or check against going out of bounds, to allow me to keep the while(true) loop going, but I cant figure it out.
If I increase the number of objects in the pool to a higher number (i.e. 11) then the first enemy reaches the end of the path before the last pool enemy spawns, and its not a problem, but this leads to way too many enemies on screen at once.
Is there a way to safely exit the the EnableObjectsInPool loop, if all Object are active in the hierarchy?
Any suggestions?

EDIT: I just realized I can simply increase the delay of the coroutine, to properly time the enemy spawning with fewer enemies… But, my question still stands…

Index out of bounds exceptions happen when you’re trying to access an item in an array that hasn’t been initialized.

For example, say you’ve made an array with the size of 2 items. items. That lets you use items[0] and items[1], but if you try to access items[2], you’ll get an Index out of bounds exception. So I’m guessing you’ve got a logic issue (probably an off by one issue) in your code.

Hey Michael, Thanks again, for the reply. I solved the error issue I was having when all objects in the Pool were active, with this snippet (posting incase anyone else notices the issue).

void EnableObjectsInPool()
    {
        for (int i = 0; 1 < pool.Length - 1; i++)
        {
            if(i>pool.Length-1)//I added this check to return out if the Index is out of range.
            { return; }
            if (pool[i].activeInHierarchy == false)
            {
                pool[i].SetActive(true);
                
                return;
                
            }
           
        }
    }

The check I added prevents the code from breaking, if there are no more inactive objects in the pool.

1 Like

I think you’ll find it’ll also work if you switch the 1 > pool. to i < pool.

oops, that was a Typo, thanks! lol.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms