1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine;
public class ObjectPoolManager : MonoBehaviour { public static List<PooledObjectInfo> ObjectPools = new List<PooledObjectInfo>();
public static GameObject SpawnObject(GameObject objectToSpawn, Vector3 spawnPosition,Quaternion spawnQuaternion) { PooledObjectInfo pool = ObjectPools.Find(p => p.LookupString == objectToSpawn.name);
if(pool == null) { pool = new PooledObjectInfo() { LookupString = objectToSpawn.name }; ObjectPools.Add(pool); }
GameObject spawnableObj = pool.inactiveObjects.FirstOrDefault();
if(spawnableObj == null) { spawnableObj = Instantiate(objectToSpawn, spawnPosition, spawnQuaternion); } else { spawnableObj.transform.position = spawnPosition; spawnableObj.transform.rotation = spawnQuaternion; pool.inactiveObjects.Remove(spawnableObj); spawnableObj.SetActive(true); }
return spawnableObj; }
public static void ReturnObjectToPool(GameObject obj) { string goName = obj.name; if (goName.EndsWith("(Clone)")) goName = goName.Substring(0, goName.Length - 7);
PooledObjectInfo pool = ObjectPools.Find(p => p.LookupString == goName);
if(pool == null) { Debug.LogWarning(goName+" is not belone to any pool!"); } else { obj.SetActive(false); pool.inactiveObjects.Add(obj); } } }
public class PooledObjectInfo { public string LookupString; public List<GameObject> inactiveObjects = new List<GameObject>(); }
|