对象池的简单使用

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

}

  

posted @ 2019-01-07 23:19  TheBoy_24  阅读(252)  评论(0编辑  收藏  举报