using System; using System.Collections.Generic; using UnityEngine; namespace ET.Util { public static class GameObjectPoolHelper { private static Dictionary poolDict = new Dictionary(); public static void InitPoolFromPrefab(GameObject pb, int size, PoolInflationType type = PoolInflationType.DOUBLE) { string poolName = pb.name; if (poolDict.ContainsKey(poolName)) { return; } else { try { if (pb == null) { Debug.LogError("[ResourceManager] Invalide prefab name for pooling :" + poolName); return; } poolDict[poolName] = new GameObjectPool(poolName, pb, GameObject.Find("Global/PoolRoot"), size, type); } catch (Exception e) { Debug.LogError(e); } } } /// /// Returns an available object from the pool /// OR null in case the pool does not have any object available & can grow size is false. /// /// /// public static GameObject SpawnGameObject(GameObject prefab, bool autoActive = true, int autoCreate = 1) { GameObject result = null; var poolName = prefab.name; if (!poolDict.ContainsKey(poolName) && autoCreate > 0) { InitPoolFromPrefab(prefab, autoCreate, PoolInflationType.INCREMENT); } if (poolDict.ContainsKey(poolName)) { GameObjectPool pool = poolDict[poolName]; result = pool.GetAvailableObject(autoActive); //scenario when no available object is found in pool #if UNITY_EDITOR if (result == null) { Debug.LogWarning("[ResourceManager]:No object available in " + poolName); } #endif } #if UNITY_EDITOR else { Debug.LogError("[ResourceManager]:Invalid pool name specified: " + poolName); } #endif return result; } /// /// Return obj to the pool /// /// public static void ReturnObjectToPool(GameObject go) { PoolObject po = go.GetComponent(); if (po == null) { #if UNITY_EDITOR Debug.LogWarning("Specified object is not a pooled instance: " + go.name); #endif } else { GameObjectPool pool = null; if (poolDict.TryGetValue(po.poolName, out pool)) { pool.ReturnObjectToPool(po); } #if UNITY_EDITOR else { Debug.LogWarning("No pool available with name: " + po.poolName); } #endif } } /// /// Return obj to the pool /// /// public static void ReturnTransformToPool( Transform t) { if (t == null) { #if UNITY_EDITOR Debug.LogError("[ResourceManager] try to return a null transform to pool!"); #endif return; } ReturnObjectToPool(t.gameObject); } } }