Пример #1
0
        //回收
        public bool Recycle(GameObject obj)
        {
            if (obj == null)
            {
                return(false);
            }
            ObjectPoolable objectPoolable = obj.GetComponent <ObjectPoolable>();

            if (objectPoolable == null || objectPoolable.IsRecycled)
            {
                return(false);
            }
            obj.SetActive(false);
            objectPoolable.IsRecycled = true;

            Stack <GameObject> values;

            if (!cachedObjects.TryGetValue(objectPoolable.PoolKey, out values))
            {
                values = new Stack <GameObject>();
                cachedObjects.Add(objectPoolable.PoolKey, values);
            }
            values.Push(obj);
            return(true);
        }
Пример #2
0
        //分配
        public GameObject Allocate(string name)
        {
            GameObject obj = PopFromPool(name);

            if (obj == null)
            {
                GameObject asset = ResourceManager.Instance.LoadAsset <GameObject>(name);
                if (asset != null)
                {
                    obj       = Instantiate(asset);
                    obj.name += "(Pool)";
                }
            }
            if (obj == null)
            {
                Debug.LogError("从缓存池中获取对象失败:" + name);
            }
            else
            {
                ObjectPoolable objectPoolable = obj.GetComponent <ObjectPoolable>();
                if (objectPoolable == null)
                {
                    objectPoolable = obj.AddComponent <ObjectPoolable>();
                }
                objectPoolable.PoolKey    = name;
                objectPoolable.IsRecycled = false;
                obj.SetActive(true);
            }
            return(obj);
        }