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);
            }
        }
    
    }
    

      

  • 相关阅读:
    事务的原理 学习笔记
    JAVA并发-从缓存一致性说volatile 讲的很好
    【mysql】mysql有哪些权限
    spring data jpa mysql 悲观锁
    Mysterious Bacteria LightOJ
    Harmonic Number LightOJ
    Aladdin and the Flying Carpet LightOJ
    Pairs Forming LCM LightOJ
    Harmonic Number (II) LightOJ
    Goldbach`s Conjecture LightOJ
  • 原文地址:https://www.cnblogs.com/zhaodadan/p/10236369.html
Copyright © 2011-2022 走看看