init
This commit is contained in:
commit
16da8e4dde
333 changed files with 109229 additions and 0 deletions
63
Assets/Scripts/ObjectPooler.cs
Normal file
63
Assets/Scripts/ObjectPooler.cs
Normal file
|
@ -0,0 +1,63 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
public class ObjectPooler : MonoBehaviour{
|
||||
|
||||
[System.Serializable]
|
||||
public class Pool{
|
||||
public string tag;
|
||||
public GameObject prefab;
|
||||
public int size;
|
||||
}
|
||||
|
||||
#region Singleton
|
||||
public static ObjectPooler Instance;
|
||||
|
||||
private void Awake(){
|
||||
Instance = this;
|
||||
}
|
||||
#endregion
|
||||
|
||||
public List<Pool> pools;
|
||||
public Dictionary<string, Queue<GameObject>> poolDictionary;
|
||||
|
||||
// Start is called before the first frame update
|
||||
void Start(){
|
||||
poolDictionary = new Dictionary<string, Queue<GameObject>>();
|
||||
|
||||
foreach (Pool pool in pools){
|
||||
Queue<GameObject> objectPool = new Queue<GameObject>();
|
||||
|
||||
for (int i = 0; i < pool.size; i++){
|
||||
GameObject obj = Instantiate(pool.prefab, gameObject.transform);
|
||||
obj.SetActive(false);
|
||||
objectPool.Enqueue(obj);
|
||||
}
|
||||
|
||||
poolDictionary.Add(pool.tag, objectPool);
|
||||
}
|
||||
}
|
||||
|
||||
public GameObject SpawnFromPool(string tag, Vector3 position, Quaternion rotation){
|
||||
if (!poolDictionary.ContainsKey(tag)){
|
||||
Debug.LogWarning("Pool with tag " + tag + " doesn't excist.");
|
||||
return null;
|
||||
}
|
||||
GameObject objectToSpawn = poolDictionary[tag].Dequeue();
|
||||
|
||||
objectToSpawn.SetActive(true);
|
||||
objectToSpawn.transform.position = position;
|
||||
objectToSpawn.transform.rotation = rotation;
|
||||
|
||||
IPooledObject pooledObj = objectToSpawn.GetComponent<IPooledObject>();
|
||||
|
||||
if (pooledObj != null){
|
||||
pooledObj.OnObjectSpawn();
|
||||
}
|
||||
|
||||
poolDictionary[tag].Enqueue(objectToSpawn);
|
||||
|
||||
return objectToSpawn;
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue