using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.Events; using GameCore; namespace GameLogic { /// /// 对象池管理器,分普通类对象池+资源游戏对象池 /// public class ObjectPoolManager : UnitySingleton { private Transform m_PoolRootObject = null; private Dictionary m_ObjectPools = new Dictionary(); private Dictionary m_GameObjectPools = new Dictionary(); Transform PoolRootObject { get { if (m_PoolRootObject == null) { var objectPool = new GameObject("ObjectPool"); objectPool.transform.SetParent(transform); objectPool.transform.localScale = Vector3.one; objectPool.transform.localPosition = Vector3.zero; m_PoolRootObject = objectPool.transform; } return m_PoolRootObject; } } public GameObjectPool CreatePool(string poolName, int initSize, GameObject prefab,bool isAutoCreate=true) { var pool = new GameObjectPool(poolName, prefab, initSize, PoolRootObject, isAutoCreate); m_GameObjectPools[poolName] = pool; return pool; } public GameObjectPool GetPool(string poolName) { if (m_GameObjectPools.ContainsKey(poolName)) { return m_GameObjectPools[poolName]; } return null; } public GameObject Get(string poolName,bool isActive=false) { GameObject result = null; if (m_GameObjectPools.ContainsKey(poolName)) { GameObjectPool pool = m_GameObjectPools[poolName]; result = pool.NextAvailableObject(isActive); if (result == null) { Debug.LogError("No object available in pool. Consider setting fixedSize to false.: " + poolName); } } else { Debug.LogError("Invalid pool name specified: " + poolName); } return result; } public void Release(string poolName, GameObject go) { if (m_GameObjectPools.ContainsKey(poolName)) { GameObjectPool pool = m_GameObjectPools[poolName]; pool.ReturnObjectToPool(poolName, go); } else { Debug.LogWarning("No pool available with name: " + poolName); } } ///----------------------------------------------------------------------------------------------- public ObjectPool CreatePool(UnityAction actionOnGet, UnityAction actionOnRelease) where T : class { var type = typeof(T); var pool = new ObjectPool(actionOnGet, actionOnRelease); m_ObjectPools[type.Name] = pool; return pool; } public ObjectPool GetPool() where T : class { var type = typeof(T); ObjectPool pool = null; if (m_ObjectPools.ContainsKey(type.Name)) { pool = m_ObjectPools[type.Name] as ObjectPool; } return pool; } public T Get() where T : class { var pool = GetPool(); if (pool != null) { return pool.Get(); } return default(T); } public void Release(T obj) where T : class { var pool = GetPool(); if (pool != null) { pool.Release(obj); } } public void DestoryAllObjectPool() { m_ObjectPools.Clear(); } public void DestoryAllGameObjectPool() { foreach (var pool in m_GameObjectPools ) { if(pool.Value!=null) { pool.Value.ClearGameObjectPool(); } } } public void Reset() { } } }