zoukankan      html  css  js  c++  java
  • 对象池的简单使用

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class DemoPool : MonoBehaviour {
        //要实例的物体
        public GameObject monsterPrefab;  
        //存放物体的对象池 未激活
        private List<GameObject> monsterList = new List<GameObject>();
        //激活
        private List<GameObject> monsterActiveList = new List<GameObject>();
        //父物体的位置
        public Transform[] parentPosition;
        	
    	void Start () {
    
            //初始化生成3个物体
            for (int i = 0; i < 3; i++)
            {
                GameObject temp = Instantiate(monsterPrefab);
                temp.transform.SetParent(parentPosition[i], false);
                //设置激活状态  添加到未激活的List 中
                temp.SetActive(false);
                monsterList.Add(temp);
            }
    	}
    	
    	// Update is called once per frame
    	void Update () {
            if (Input.GetKeyDown(KeyCode.Space))
            {
                ShowMonsterState();
            }
            if (Input.GetKeyDown(KeyCode.Q))
            {
                RecycleInitMonster();
            }
    	}
        /// <summary>
        /// 拿到第0位 从未激活的List中移除
        /// </summary>
        private void ShowMonsterState()
        {
            if (monsterList.Count > 0)
            {
                GameObject temp = monsterList[0];
                temp.SetActive(true);
                monsterList.RemoveAt(0);
                //添加到激活的List 中
                monsterActiveList.Add(temp);
            }
            else
            {
                //如果对象池中的个数不够 就实例化 添加到激活的List 中
                GameObject temp = Instantiate(monsterPrefab);
                monsterActiveList.Add(temp);
            }
        }
        private void RecycleInitMonster()
        {
            if (monsterActiveList.Count > 0)
            {
                GameObject temp = monsterActiveList[0];
                monsterActiveList.RemoveAt(0);
                temp.SetActive(false);
                monsterList.Add(temp);
            }
        }
    
    }
    

      

  • 相关阅读:
    C#一些定义
    顺序
    针对IE8的css hack
    js 数字,金额 用逗号 隔开。数字格式化
    Ubuntu下使用Vi是方向键变乱码 退格键不能使用的解决方法
    UBUNTU中如何获得root权限
    区分IE8 、IE9 的专属css hack
    ubuntu 安装 Sublime Text 2
    PHP执行zip与rar解压缩方法
    使用ThinkPHP时,双引号导致插入数据库经过转义的处理
  • 原文地址:https://www.cnblogs.com/zhaodadan/p/10236369.html
Copyright © 2011-2022 走看看