///<summary> /// 对象池本体 ///</summary> public List<GameObject> pooledObjects; ///<summary> /// 对象池要管理的对象 ///</summary> public GameObject objectToPool; ///<summary> /// 对象池中需要初始化对象的个数 ///</summary> publicint amountToPool;
voidStart() { PoolStart(); // 初始化对象池 }
///<summary> /// 初始化对象池,克隆对象并将它们添加到列表中 ///</summary> voidPoolStart() { pooledObjects = new List<GameObject>(); for (int i = 0; i < amountToPool; i++) { GameObject obj = (GameObject)Instantiate(objectToPool); obj.SetActive(false); pooledObjects.Add(obj); obj.transform.SetParent(this.transform); // 设置其父对象是 脚本所附加对象 } }
GameObject GetPooledObject() { // For as many objects as are in the pooledObjects list for (int i = 0; i < pooledObjects.Count; i++) { // if the pooled objects is NOT active, return that object if (!pooledObjects[i].activeInHierarchy) { return pooledObjects[i]; } } // otherwise, return null returnnull; }