對象池

代碼

using System.Collections.Generic;
using UnityEngine;
public class ObjectPool : MonoBehaviour
{
    static Queue<GameObject> pool = new Queue<GameObject>();//使用隊列,先進先出,避免連續生成同一個對象
    static Transform tran;
    static GameObject model;
    void Awake()
    {
        tran = transform;
        model = Resources.Load("Prefab/BaseCube") as GameObject;//加載
        Expand();
    }
    static void Expand()
    {
        GameObject obj = null;
        for (int index = 0; index < 50; index++)
        {
            obj = Instantiate(model);
            obj.transform.SetParent(tran);
            obj.SetActive(false);
            pool.Enqueue(obj);
        }
    }
    public static GameObject GetObject()//得到一個對象
    {
        if (pool.Count <= 0)//池子沒有對象,擴展
            Expand();
        GameObject obj = pool.Dequeue();//得到隊列底部的對象
        obj.SetActive(true);
        Debug.Log(pool.Count);
        return obj;
    }
    public static void PushEgg(GameObject obj)//回收一個對象
    {
        obj.SetActive(false);
        if (pool.Contains(obj))//重複的不添加?。。。
            return;
        pool.Enqueue(obj);
    }
}

使用

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

public class CreateMap : MonoBehaviour
{
    void Start()
    {
        for (int index = 0; index < 10; index++)
        {
            for (int count = 0; count < 10; count++)
            {
                GameObject game = ObjectPool.GetObject();
                if ((count + index) % 2 != 0)
                    game.transform.position = new Vector3(index, 0, count);
                else
                    ObjectPool.PushEgg(game);
            }
        }
    }
}

結果

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章