Unity 对象池之ObjectPool

来源:互联网 发布:淘宝听诊器 编辑:程序博客网 时间:2024/06/04 19:17
using System;using System.Collections.Generic;using UnityEngine;using System.Text;public class ObjectPool{    //资源目录    public string ResourseDir = "";    //字典    Dictionary<string, SubPool> m_pools = new Dictionary<string, SubPool>();    //取对象    public GameObject Spwan(string name)    {        if(!m_pools.ContainsKey(name))        {            RegisterNew(name);        }        SubPool pool = m_pools[name];        return pool.OnSpwan();    }    //回收对象    public void UnSpawn(GameObject go)    {        SubPool pool = null;        foreach(SubPool  p in m_pools.Values)        {            if(p.Contains(go))            {                pool = p;                break;            }        }        pool.OnUnSpwan(go);    }    //回收所有对象    public void UnSpwanAll()    {        foreach(SubPool p in m_pools.Values)        {            p.SwpanAll();        }    }    //创建新子对象池    void RegisterNew(string name)    {        //预设路径        string Path = "";        if (string.IsNullOrEmpty(ResourseDir))        {            Path = name;        }        else        {            Path = "/" + name;        }        //加载预设        GameObject perfab = Resources.Load<GameObject>(Path);        //创建子对象池        SubPool pool = new SubPool(perfab);        m_pools.Add(pool.Name, pool);    }}