protected virtual void CreatePools() { for (int i = 0; i < objectsPrefab.Length; i++) { IPooledObject pooledObject = objectsPrefab[i].GetComponent <IPooledObject>(); if (pooledObject == null) { Debug.LogError(objectsPrefab[i].name + " - This prefab doesn't implement 'IPooledObject'. " + "Aren't you forgeting something?"); return; } Queue <GameObject> pooledObjectsQueue = new Queue <GameObject>(); if (pools.ContainsKey(pooledObject.GetType())) { pooledObjectsQueue = pools[pooledObject.GetType()]; } for (int j = 0; j < pooledObject.AmountToPool; j++) { GameObject newObject = Instantiate(objectsPrefab[i]); newObject.transform.parent = this.transform; newObject.GetComponent <IPooledObject>().Pool = this; newObject.SetActive(false); listOfAllObjects.Add(newObject); pooledObjectsQueue.Enqueue(newObject); } pools[pooledObject.GetType()] = pooledObjectsQueue; } }
/// <summary> /// 释放对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="pooledObject"></param> public void ReleaseObject(IPooledObject pooledObject) { Type type = pooledObject.GetType(); IObjectPool objectPool = GetObjectPool(type); if (objectPool == null) { objectPool = RegisterObjectPool(type); } objectPool.Release(pooledObject); }