对象池技术

来源:互联网 发布:手游答器软件 编辑:程序博客网 时间:2024/06/01 10:47

对象池用于有大量对象的创建和销毁的场景

原理:

当我们大量的复用一个预制体,创建一个对象然后在特定的条件时让其销毁。比如发射子弹/生成敌人等等,在克隆一个游戏对象时

子对象池

using UnityEngine;using System.Collections.Generic;public class SubPool{    private GameObject prefab;    Transform tr;    private List<GameObject> subPoolList = new List<GameObject>();    public SubPool(GameObject go,Transform tr)    {        prefab = go;        this.tr = tr;    }    //取对象    public GameObject Spawn()    {        GameObject go;        foreach (GameObject item in subPoolList)        {            if (!item.activeSelf)            {                item.SetActive(true);                return item;            }        }        go = GameObject.Instantiate<GameObject>(prefab);        go.transform.parent = tr;        go.SetActive(true);        subPoolList.Add(go);        return go;    }    //回收对象    public void UnSpawn(GameObject go)    {        if (subPoolList.Contains(go))        {            go.SendMessage("Reset", SendMessageOptions.DontRequireReceiver);            go.SetActive(false);        }        else        {            Debug.LogError("子对象池中没有该对象");        }    }    /// <summary>    /// 判断子对象是否包含某个对象    /// </summary>    public bool  Contains(GameObject go)    {        return subPoolList.Contains(go);    }}

大对象池

using UnityEngine;using System.Collections.Generic;public class ObjectPool : SingleTemplate<ObjectPool>{    private Dictionary<string, SubPool> objectPoolDic;    protected override void Awake()    {        base.Awake();        objectPoolDic = new Dictionary<string, SubPool>();    }    //取对象    public GameObject Spawn(string name, GameObject prefab)    {        GameObject go = null;        if (!objectPoolDic.ContainsKey(name))//没有子对象池        {            CreateSubPool(name, prefab);        }        go = objectPoolDic[name].Spawn();        return go;    }    //回收对象    public void UnSpawn(GameObject go)    {        foreach (SubPool item in objectPoolDic.Values)        {            if (item.Contains(go))            {                item.UnSpawn(go);                return;            }        }        Debug.LogError("没有该子对象池,该对象不是我创建的");    }    private void  CreateSubPool(string name,GameObject prefab)    {        SubPool sub = new SubPool(prefab, transform);        objectPoolDic.Add(name, sub);    }}




原创粉丝点击