1. 程式人生 > >對象池的簡單使用

對象池的簡單使用

lis dem led sharp mar i++ rac gen erp

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

}

  

對象池的簡單使用