I’m wondering, how do people normally make a pool for object that has multiple types? in my case i wanted to do an object pool that could support multiple types of projectile. the projectile will behave in different ways and also have different mesh.
what i had in mind is have the projectile derive the off a base and pool that instead, then when i grab a projectile from the pool i’ll reassign mesh and instantiate it as the type of projectile i want.
GenericProjectile tempProjectile = ProjectilePool.instance.GetProjectile();
tempProjectile = new CannonShell();
i think this is the way to go but i feel like i’m missing something. any guidance will be much appreciated.
I was in ur situation a few weeks ago, i wrote a pool script for multiple objects in a pool with diffrent amounts of each.
It also has a fallback where if you create more object then you first created it will create a new one of that object and add it to the pool.
using UnityEngine;
using System.Collections.Generic;
[System.Serializable]
public class PooledObject
{
public GameObject Object;
public int Amount;
}
public class Pool : MonoBehaviour
{
public static Pool Instance;
public PooledObject[] Objects;
private List<GameObject>[] pool;
void Awake()
{
Instance = this;
}
void Start()
{
GameObject temp;
pool = new List<GameObject>[Objects.Length];
for (int count = 0; count < Objects.Length; count++)
{
pool[count] = new List<GameObject>();
for (int num = 0; num < Objects[count].Amount; num++)
{
temp = (GameObject)Instantiate(Objects[count].Object, new Vector3(0.0f, 1000.0f, 0.0f), Quaternion.identity);
temp.SetActive(false);
temp.transform.parent = transform;
pool[count].Add(temp);
}
}
}
public GameObject Activate(int id, Vector3 position, Quaternion rotation)
{
for (int count = 0; count < pool[id].Count; count++)
{
if (!pool[id][count].activeSelf)
{
GameObject currObj = pool[id][count];
Transform currTrans = currObj.transform;
currObj.SetActive(true);
currTrans.position = position;
currTrans.rotation = rotation;
return currObj;
}
}
GameObject newObj = Instantiate(Objects[id].Object) as GameObject;
Transform newTrans = newObj.transform;
newTrans.position = position;
newTrans.rotation = rotation;
newTrans.parent = transform;
pool[id].Add(newObj);
return newObj;
}
public void Deactivate(GameObject obj)
{
obj.SetActive(false);
}
}
Then in another script if you need an object do this:
// Your object id
int id = 0;
// Your position
Vector3 position = Vector3.zero;
// Your rotation
Quaternion rotation = Quaternion.Eular(new Vector(0,0,0));
Pool.Instance.Activate(id, position, rotation);
And if your done with one using a timed check or whatever use:
Pool.Instance.Deactivate(gameObject);