- Home /
Spawning different prefabs randomly using Object pooling
I want to spawn 3 different types of prefab randomly through pool manager script. I found the given script when I access this script in cube Spawner script but Here It doesn't take more than one prefabs sorry for weak English .If any one get my point help thanks. Dictionary> poolDictionary = new Dictionary>(); static PoolManager _instance; public static PoolManager instance { get { if (_instance == null) { _instance = FindObjectOfType(); } return _instance; } }
public void CreatePool(GameObject prefab,int poolSize)
{
int poolKey = prefab.GetInstanceID();
if (!poolDictionary.ContainsKey(poolKey))
{
poolDictionary.Add(poolKey,new List<GameObject>());
for(int i = 0; i < poolSize; i++)
{
GameObject newObject = Instantiate(prefab);
poolDictionary[poolKey].Add(newObject);
}
}
}
public GameObject GetObject(GameObject prefab)
{
int poolKey = prefab.GetInstanceID();
if (poolDictionary.ContainsKey(poolKey))
{
List<GameObject> pool = new List<GameObject>();
for(int i = 0; i < pool.Count; i++)
{
if (!pool[i].activeInHierarchy)
{
return pool[i];
}
}
GameObject newObject = Instantiate(prefab);
poolDictionary[poolKey].Add(newObject);
return newObject;
}
return null;
}
Bellow is the script where I want to spawn different prefabs.
private void Awake() { currentPosition = cubePrefab.transform.position; } private void Start() { PoolManager.instance.CreatePool(cubePrefab, poolSize); InvokeRepeating("SpawnCubes",0f, 10f); } private void SpawnCubes() {
GameObject cubeObject = PoolManager.instance.GetObject(cubePrefab);
cubeObject.transform.position = currentPosition;
cubeObject.SetActive(true);
Vector3 newPosition = currentPosition;
newPosition.z += distance;
currentPosition = newPosition;
}
Answer by ShadyProductions · Jun 09, 2020 at 05:52 PM
Use mine: https://github.com/Venom0us/UnityObjectPooler
You can pool any object of type component, including monobehaviours like gameobject. And you can retrieve custom components by ObjectPool.GetCustom(a => lamba criteria); It is documented here: https://github.com/Venom0us/UnityObjectPooler/wiki/Documentation
And there is a small sample project included.
Your answer
Follow this Question
Related Questions
Grabbing an object from array 0 Answers
Check if GameObjects are from the same prefab? 1 Answer
hel with object pooling? 2 Answers
In need of some help with objectpooling and randomised tag setting 0 Answers