Unity - Object Pooling Reference
Using UnityEngine.ObjectPool
This is a technique I learnt from this youtube video.
public class BulletHellManager: Singleton<BulletHellManager> {
ObjectPool<Bullet> bulletPool;
readonly List<Bullet> activeProjectiles = new List<Bullet>();
readonly List<Bullet> bulletsToReturn = new List<Bullet>();
void Start() {
bulletPool = new ObjectPool<Bullet>(
createFunc: () => {
GameObject bulletObj = Instantiate(bulletPrefab, bulletOrigin.transform, true);
bulletObj.SetActive(false);
return bulletObj.GetOrAdd<Bullet>();
},
actionOnGet: bullet => bullet.gameObject.SetActive(true),
actionOnRelease: bullet => bullet.gameObject.SetActive(false),
actionOnDestroy: bullet => Destroy(bullet.gameObject),
collectionCheck: false,
defaultCapacity: bulletCount,
maxSize: bulletCount * 10
)
}
void Update() {
for (int i = 0; i < activeProjectiles.Count; i++) {
Bullet bullet = activeProjectiles[i];
if (bullet.HasTravelledMaxDistance()) {
ReturnBullet(bullet);
}
}
}
void LateUpdate() {
foreach (var bullet in bulletsToReturn) {
bulletPool.Release(bullet);
}
bulletsToReturn.Clear();
}
void OnDestroy() {
bulletPool.Dispose();
}
void ReturnBullet(Bullet bullet) {
bulletsToReturn.Add(bullet);
activeProjectiles.Remove(bullet);
}
public void SpawnBullet() {
Bullet bullet = bulletPool.Get();
bullet.Init(); // way to implement the direction to fly
activeProjectiles.Add(bullet);
}
}
Using Simple Scripts
Referencing Unity’s Introduction to Object Pooling, we can use the following scripts to manually control our instantiated objects using List.
public static ObjectPool SharedInstance;
public List<GameObject> pooledObjects;
public GameObject objectToPool;
public int amountToPool;
void Awake()
{
SharedInstance = this;
}
void Start()
{
pooledObjects = new List<GameObject>();
GameObject tmp;
for(int i = 0; i < amountToPool; i++)
{
tmp = Instantiate(objectToPool);
tmp.SetActive(false);
pooledObjects.Add(tmp);
}
}
public GameObject GetPooledObject()
{
for(int i = 0; i < amountToPool; i++)
{
if(!pooledObjects[i].activeInHierarchy)
{
return pooledObjects[i];
}
}
return null;
}
To use the object pool, use this
GameObject bullet = ObjectPool.SharedInstance.GetPooledObject();
if (bullet != null) {
bullet.transform.position = turret.transform.position;
bullet.transform.rotation = turret.transform.rotation;
bullet.SetActive(true);
}