/// <summary> /// 获取对象池中可以使用的对象。 /// </summary> public GameObjectPoolable Allocate() { for (int i = 0; i < pooledObjects.Count; ++i) { //每一次遍历都是从上一次被使用的对象的下一个 int Item = (currentIndex + i) % pooledObjects.Count; if (pooledObjects[Item].IsRecycled) { currentIndex = (Item + 1) % pooledObjects.Count; //返回第一个未激活的对象 pooledObjects[Item].IsRecycled = false; return(pooledObjects[Item]); } } //如果遍历完一遍对象库发现没有闲置对象且对象池未达到数量限制 if (CurrentCount < maxCount) { GameObjectPoolable info = Create(template); info.IsRecycled = false; return(info); } return(null); }
/// <summary> /// 回收 /// </summary> public bool Recycle(GameObjectPoolable poolObj) { if (poolObj == null || poolObj.IsRecycled) { return(false); } poolObj.OnRecycled(); return(true); }
/// <summary> /// 为对象池新增一个对象 /// </summary> private GameObjectPoolable Create(GameObject template, bool isShow = true) { GameObjectPoolable info = new GameObjectPoolable(GameObject.Instantiate(template, objParent)); pooledObjects.Add(info); if (!isShow) { info.obj.SetActive(false); } return(info); }