단순 대상 캐시 실현

10782 단어 unity
모두가 알다시피 unity는 부하를 많이 먹는다. 왜냐하면 대량의 게임object의 스크립트가 unity의 생명주기에 들어가기 때문에 이럴 때 물체를 저장하기 위해 캐시 탱크가 필요하다.
https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
    private Dictionary<System.Type, List<GameObject>> dicpool = new Dictionary<System.Type, List<GameObject>>();
    public int Objmaxcount;
// 
    private static pool instance;
    public static pool Instance
    {
        get
        {
            if (instance == null)
                instance = new pool();
            return instance;
        }
    }
    void Awake()
    {

        DontDestroyOnLoad(gameObject);
        instance = this;
    }
    public GameObject CreateObject(GameObject obj)
    {
        List<GameObject> tmplist = new List<GameObject>();
        if (dicpool.ContainsKey(obj.GetType()) && dicpool[obj.GetType()].Count > 0)
        {
            tmplist = dicpool[obj.GetType()];
            tmplist[0].SetActive(true);
            GameObject go = tmplist[0];
            tmplist.Remove(go);
            return go;
        }
        for (int i = 0; i < Objmaxcount; i++)
        {
            GameObject go = Instantiate(obj);
            go.SetActive(false);
            tmplist.Add(go);
        }
        dicpool.Add(obj.GetType(), tmplist);
        return Instantiate(obj);

    }
    public void DestroyObject(GameObject obj)
    {
        if (dicpool.ContainsKey(obj.GetType()))
        {
            List<GameObject> tmplist = dicpool[obj.GetType()];
            if (tmplist.Count >= Objmaxcount)
            {
                Destroy(obj);
                return;
            }
            tmplist.Add(obj);
            obj.SetActive(false);
        }
        else
        {
            Destroy(obj);
        }
    }

좋은 웹페이지 즐겨찾기