Unity对象池的运用

  为了节省内存,避免同种物体的反复生成销毁,衍生了对象池的概念
  对象池实现的简单示例如下:
Unity对象池的运用_第1张图片
代码如下:

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

你可能感兴趣的:(计算机语言,Unity)