So I’ve finally managed to wrap my head around pooling, and I got it to work now successfully. However, I feel there has to be a cleaner method of keeping track of objects that my enemy spawner can use. (ones that are obviously currently inactive off screen)
Right now, inside function update I’m calling this check every frame.
currentEnemy01 = enemyPrefabs01[currentEnemy01Tracker];
if (currentEnemy01.activeSelf)
{
currentEnemy01Tracker ++;
}
if (currentEnemy01Tracker >= enemyPrefabs01.Length)
{
currentEnemy01Tracker = 0;
}
currentEnemy01Tracker is obviously an int variable I use to keep track of which item I can use next. But the thought of running this check every frame seems a bit on the overkill side.
I’ve read this answer about a half dozen times now and I still don’t fully understand it which is why I ended up just making my own based off of a youtube tutorial I found.
What I have right now is working great. I just need a more efficient way of finding the next available object in the pool, which could be any of them because enemies do not typically tend to die in a uniformed order.
You want to use a Stack object onto which you push your instances and Pop them off when you need them.
In javascript you would do this (perhaps in a script call PoolManager):
import System.Collections.Generic;
...
public static pool = new Stack.<Transform>();
public prefab : Transform;
for(var i = 0; i < 10; i++) {
var instance : Transform = Instantiate(prefab);
instance.gameObject.SetActive(false);
pool.Push(instance);
}
Now you can check if you have any:
if(PoolManager.pool.Count > 0) { ...
And get one:
var obj = PoolManager.pool.Pop();
obj.gameObject.SetActive(true);
checking that last link and now looking at the api for array's in Unity script it appears that pushing and pulling from the array are built in to the array function itself? http://docs.unity3d.com/Documentation/ScriptReference/Array.html I'm new to this all so I'm just curious if the array system does have stack method built into it?
Thanks for the info!
– Rick74Sorry that this is a few days late, but I'm having trouble finding an example of this written in Unity/Javascript. I found this; http://msdn.microsoft.com/en-us/library/3278tedw(v=vs.100).aspx Is stack a c# thing? I also found this; http://javascript.about.com/library/blstack.htm While that is referring to pure Javascript, I'm curious if that also applies to Unityscript as well?
– Rick74Stack is a .NET thing so mostly doc'd in Cs but works fine in js
– whydoidoitchecking that last link and now looking at the api for array's in Unity script it appears that pushing and pulling from the array are built in to the array function itself? http://docs.unity3d.com/Documentation/ScriptReference/Array.html I'm new to this all so I'm just curious if the array system does have stack method built into it?
– Rick74Don't use the Unity JS Array class; it's slow and untyped.
– Eric5h5