首页 > 代码库 > GameObjectPool——Unity中的对象池

GameObjectPool——Unity中的对象池

这里介绍一种对象池的写法。它的优点在于无论取出还是插入游戏物体都是常数量时间。

using UnityEngine;using System.Collections;using System.Collections.Generic;//对象池public class GameObjectPool : MonoSingleton<GameObjectPool>{    /// <summary>可能存放多个种类的对象,每个种类有多个对象 </summary>    private Dictionary<string, LinkedList<GameObject>> Pool = new Dictionary<string, LinkedList<GameObject>>();    private Dictionary<GameObject, LinkedListNode<GameObject>> ObjectDic = new Dictionary<GameObject, LinkedListNode<GameObject>>();    /// <summary>增加物体进入池(按类别增加)</summary>    public void Add(string key, GameObject go)    {        //1.如果key在容器中存在,则将go加入对应的列表        //2.如果key在容器中不存在,是先创建一个列表,再加入        if (!Pool.ContainsKey(key))        {            Pool.Add(key, new LinkedList<GameObject>());        }        LinkedListNode<GameObject> t = new LinkedListNode<GameObject>(go);        Pool[key].AddLast(t);        ObjectDic[go] = t;    }    /// <summary>销毁物体(将对象隐藏)</summary>    public void MyDestory(string key, GameObject destoryGo)    {        //设置destoryGo隐藏        ObjectDic[destoryGo].Value.SetActive(false);        LinkedListNode<GameObject> temp = ObjectDic[destoryGo];        Pool[key].Remove(temp);        Pool[key].AddFirst(temp);    }    /// <summary>将对象归入池中<summary>    public void MyDestory(string key, GameObject tempGo, float delay)    {        //开启一个协程        StartCoroutine(DelayDestory(key, tempGo, delay));    }    /// <summary>延迟销毁</summary>    private IEnumerator DelayDestory(string key, GameObject destoryGO, float delay)    {        //等待一个延迟的时间        yield return new WaitForSeconds(delay);        MyDestory(key, destoryGO);    }    /// <summary>创建一个游戏物体到场景 </summary>    public GameObject CreateObject(string key, GameObject go, Vector3 position, Quaternion quaternion)    {        //先找是否有可用的,如果没有则创建,如果有找到后设置好位置,朝向再返回        GameObject tempGo = Pool[key].First.Value;        if (tempGo.activeSelf == false)        {            tempGo.transform.position = position;            tempGo.transform.rotation = quaternion;            tempGo.SetActive(true);            Pool[key].RemoveFirst();            Pool[key].AddLast(ObjectDic[tempGo]);        }        else        {            tempGo = GameObject.Instantiate(go, position, quaternion) as GameObject;            Add(key, tempGo);        }        return tempGo;    }    /// <summary>清空某类游戏对象</summary>    public void Clear(string key)    {        var t = Pool[key].First;        while (t.Next!=null)        {            ObjectDic.Remove(t.Value);        }        Pool.Remove(key);    }    /// <summary>清空池中所有游戏对象</summary>    public void ClearAll()    {        ObjectDic.Clear();        Pool.Clear();    }}

  

  

GameObjectPool——Unity中的对象池