对象池的简单使用
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class DemoPool : MonoBehaviour {//要實(shí)例的物體public GameObject monsterPrefab; //存放物體的對象池 未激活private List<GameObject> monsterList = new List<GameObject>();//激活private List<GameObject> monsterActiveList = new List<GameObject>();//父物體的位置public Transform[] parentPosition;void Start () {//初始化生成3個(gè)物體for (int i = 0; i < 3; i++){GameObject temp = Instantiate(monsterPrefab);temp.transform.SetParent(parentPosition[i], false);//設(shè)置激活狀態(tài) 添加到未激活的List 中temp.SetActive(false);monsterList.Add(temp);}}// Update is called once per framevoid 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{//如果對象池中的個(gè)數(shù)不夠 就實(shí)例化 添加到激活的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);}}}
轉(zhuǎn)載于:https://www.cnblogs.com/zhaodadan/p/10236369.html
總結(jié)
- 上一篇: 性能优化(数据库设计原则)
- 下一篇: 要想工作效率高,我们到底需要多少睡眠?