I am doing an GameObject pool for my game for 64 instances of a prefab, and I never know how many instances will be used simultaneously in the game.
I can either choose:
a generic list List where I just use .Add() and .Remove
a builtin array where I would have to run a While loop to detect the first element that is empty or not, in order to save or remove a GameObject in the array.
I use a Queue. But you can use a List, they are almost the same.
Lists are just arrays on the inside anyway. Why bother implementing some of the already implemented List functions when you can just use a List.
Just make sure you use it like a Stack as putting objects into the front or middle and taking from the front or middle is more expensive than from the end.
pseudo code:
void Push( T obj )
{
List.Add(obj)
}
T Pop()
{
if( Count == 0 )
{
return new T()
}
int index = List.Count-1
T obj = List[index ]
List.RemoveAt(index)
return obj
}
If you can have a guess as you how many objects you may want to have in the pool at one time you can also reverse memory for the list so that it doesn’t make expensive allocates to grow its internal array while your game is running.
List<T> reserveSomeSpace = new List<T>(10);// 10 tells the list to make an array of size 10,
//don't worry if you need more it'll automatically double if you add an 11th item.