Unity 对象池-01

Unity 对象池-01

PoolManager.cs用于创建对象池,及在对象池中添加对象、取出对象
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// 
/// 对象池
/// 
public class PoolManager : MonoBehaviour
{
    public List pooList = new List();

    public GameObject PoolPrefab;

    // TODO 从Json中读取赋值
    public int MaxCount = 100;//最大数量。

    /// 
    /// 向对象池中添加对象
    /// 
    /// 
    public void Push(GameObject obj)
    {
        if (pooList.Count < MaxCount)
        {
            pooList.Add((obj));
        }
        else
        {
            Destroy(obj);
        }
    }

    /// 
    /// 从对象池中取出对象
    /// 
    /// 
    public GameObject Pop()
    {
        if (pooList.Count > 0)
        {
            GameObject obj = pooList[0];
            pooList.RemoveAt(0);
            return obj;
        }
        return Instantiate(PoolPrefab);//池为空,实例化一个
    }

    public void Clear()
    {
        pooList.Clear();
    }
}

PoolTest.cs创建一个新的对象池,用于管理不在对象池中的对象。根据鼠标操作对 对象池中的对象进行操作
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PoolTest : MonoBehaviour
{
    //管理当前存在的对象(不在对象池中的对象)
    public List PoolList = new List();

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            //创建
            //从对象池取出
            GameObject obj = GetComponent().Pop();
            PoolList.Add(obj);
            obj.SetActive(true);
        }

        if (Input.GetMouseButtonDown(1))
        {
            //删除
            //放到对象池
            if (PoolList.Count > 0)
            {
                GetComponent().Push(PoolList[0]);
                PoolList[0].SetActive(false);
                PoolList.RemoveAt(0);
            }
        }
    }
}

你可能感兴趣的:(Unity,Unity,C#)