对象池

来源:互联网 发布:网络订单之小鸭子 编辑:程序博客网 时间:2024/06/09 17:44
using UnityEngine;using System.Collections.Generic;public class PoolManager : Singleton<PoolManager> {    private Dictionary<string, Pool> _dic = new Dictionary<string, Pool>();    //生成    public GameObject Spawn(string assetType, string assetName)    {        GameObject obj;        if (_dic.ContainsKey(assetName))        {            Pool pool = _dic[assetName];            obj = pool.Spawn(assetType, assetName);        }        else        {            Pool pool = new Pool();            obj = pool.Spawn(assetType, assetName);            _dic.Add(assetName, pool);        }        return obj;    }    //回收    public void Recycle(GameObject obj)    {        if(_dic.ContainsKey(obj.name))        {            _dic[obj.name].Recycle(obj);        }    }}using UnityEngine;using System.Collections.Generic;public class Pool  {    private List<GameObject> list = new List<GameObject>();    //出货    public GameObject Spawn(string assetType,string assetName)    {        GameObject obj;        if(list.Count > 0)        {            obj = list[0];            list.Remove(obj);            obj.SetActive(true);        }        else        {            string path = assetType + "/" + assetName;            obj = GameObject.Instantiate(Resources.Load<GameObject>(path));        }        obj.name = assetName;        return obj;    }    //回收    public void Recycle(GameObject obj)    {        list.Add(obj);        obj.SetActive(false);    }}
原创粉丝点击