1. 程式人生 > >Unity物件池的運用

Unity物件池的運用

  為了節省記憶體,避免同種物體的反覆生成銷燬,衍生了物件池的概念
  物件池實現的簡單示例如下:
在這裡插入圖片描述
程式碼如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectPool : MonoBehaviour
{
    //monster的預製體
    public GameObject MonsterPrefab;
    //monster的物件池
    private Stack<GameObject> monsterPool;
//在當前場景中正在使用的 啟用的monster private Stack<GameObject> activeMonsterPool; void Start() { monsterPool = new Stack<GameObject>(); activeMonsterPool = new Stack<GameObject>(); } void Update() { if (Input.GetMouseButtonDown(0)) { //獲取一個monster物件
GameObject monster = GetMonster(); monster.transform.position = new Vector3(Random.Range(-8,8),Random.Range(-3,4),0); activeMonsterPool.Push(monster); } if (Input.GetMouseButtonDown(1)) { if (activeMonsterPool.Count > 0) {
PushGameObjectToPool(activeMonsterPool.Pop()); } } } private GameObject GetMonster() { GameObject monsterTemp = null; if (monsterPool.Count > 0) { //池子中有物件 monsterTemp = monsterPool.Pop(); monsterTemp.SetActive(true); } else { //物件池中沒有物件 去例項化 monsterTemp = Instantiate(MonsterPrefab); } return monsterTemp; } // 把一個monster物件推進物件池 private void PushGameObjectToPool(GameObject monster) { monster.transform.SetParent(transform); monster.SetActive(false); monsterPool.Push(monster); } }