对象池

来源:互联网 发布:以利天诚大数据 编辑:程序博客网 时间:2024/04/30 14:26

简单对象池


大量创建销毁对象的过程可以使用对象池。比如发子弹,刷怪。背包UI

前言- 在使用前需要创建Resources文件夹。里面放相应的 prefab。


using UnityEngine;
using System.Collections;
using System.Collections.Generic;


public class Pool :MonoBehaviour {
    private static Pool instance;
    public static Pool Instance
    {
        get {
            if (instance == null)
            {
                instance = new Pool();
            }
            return instance;
        }
    }
    void Start() {
        instance = this;
    }
    private static Dictionary<string, ArrayList> pool = new Dictionary<string, ArrayList> { };
    public  Object Get(string prefabName)
    {       
        string key = prefabName ;
        Object o;
        //池中存在,则从池中取出
        if (pool.ContainsKey(key) && pool[key].Count > 0)
        {          
            ArrayList list = pool[key];
            o = list[0] as Object;
            list.Remove(o);                   
            (o as GameObject).SetActive(true);          
        }
        //池中没有则实例化gameobejct
        else
        {
            o = Instantiate(Resources.Load(prefabName));
            o.name = prefabName;
        }           
        return o;
    }




    public  Object Return(GameObject o)
    {
        string key = o.name;
        if (pool.ContainsKey(key))
        {            
            ArrayList list = pool[key];
            list.Add(o);
        }
        else
        {          
            pool[key] = new ArrayList() { o };
        }
        o.SetActive(false);
        return o;
    }
}

0 0
原创粉丝点击