• Unity3D 对象池


    ※ 对 象 池

    对象池是Unity中用于节省资源的逻辑方法;

    C# 脚本

     1 public class ObjPool : MonoBehaviour {
     2 
     3     public GameObject Monster;    //对象(预制体)
     4     private Stack<GameObject> _MonsterPool;   //对象池
     5     private List<GameObject> _ActiveMonsterList;     //需要在场景中存在的怪物的集合
     6 
     7     public Vector3 MonsterPostion;    //对象的实例化位置
     8 
     9 
    10     //赋初始值
    11     void Start () {
    12         _MonsterPool=new Stack<GameObject>();
    13         _ActiveMonsterList = new List<GameObject>();
    14         MonsterPostion=default(Vector3);
    15     }
    16     
    17     // Update is called once per frame
    18     //进行简单运行测试
    19     void Update () {         
    20         if (Input.GetMouseButtonDown(0))
    21         {
    22             GetMonster().transform.position = MonsterPostion;
    23         }
    24         if (Input.GetMouseButtonDown(1))
    25         {
    26               RecycleMonsterToPool( _ActiveMonsterList[0]);
    27         }
    28     }
    29     public GameObject GetMonster() {
    30         GameObject monster=null;
    31         if (_MonsterPool.Count>0)    //如果对象池中有实例对象,就拿出来
    32         {
    33             monster = _MonsterPool.Pop();  
    34         }
    35         else        //否则重新实例化一个
    36         {
    37             monster = Instantiate(Monster);
    38         }
    39         monster.SetActive(true);       //激活
    40         _ActiveMonsterList.Add(monster);   //将得到的对象添加的存活集合中
    41         return monster;
    42     }
    43     public void RecycleMonsterToPool(GameObject monster) {
    44         monster.SetActive(false);   //另该怪物状态失活
    45         _ActiveMonsterList.Remove(monster);   //将该怪物移出存活集合
    46 
    47         monster.transform.SetParent(transform);   //将怪物挪到对象池所在位置
    48         _MonsterPool.Push(monster);     //放入怪物对象池中
    49     }
    50 }
  • 相关阅读:
    DataTable.Compute功能
    ip的划分,超详细
    静态页 htm传参数
    [你必须知道的.NET] 第四回:后来居上:class和struct
    [你必须知道的.NET] 第八回:品味类型值类型与引用类型(上)-内存有理
    [你必须知道的.NET] 第五回:深入浅出关键字把new说透
    作废
    XML Schema <第三篇>
    XML基础<第一篇>
    NHibernate之配置文件属性说明
  • 原文地址:https://www.cnblogs.com/RainPaint/p/9964900.html
Copyright © 2020-2023  润新知