PoolManager.cs用于创建对象池,及在对象池中添加对象、取出对象
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 对象池
/// </summary>
public class PoolManager : MonoBehaviour
{
public List<GameObject> pooList = new List<GameObject>();
public GameObject PoolPrefab;
// TODO 从Json中读取赋值
public int MaxCount = 100;//最大数量。
/// <summary>
/// 向对象池中添加对象
/// </summary>
/// <param name="obj"></param>
public void Push(GameObject obj)
{
if (pooList.Count < MaxCount)
{
pooList.Add((obj));
}
else
{
Destroy(obj);
}
}
/// <summary>
/// 从对象池中取出对象
/// </summary>
/// <returns></returns>
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<GameObject> PoolList = new List<GameObject>();
void Update()
{
if (Input.GetMouseButtonDown(0))
{
//创建
//从对象池取出
GameObject obj = GetComponent<PoolManager>().Pop();
PoolList.Add(obj);
obj.SetActive(true);
}
if (Input.GetMouseButtonDown(1))
{
//删除
//放到对象池
if (PoolList.Count > 0)
{
GetComponent<PoolManager>().Push(PoolList[0]);
PoolList[0].SetActive(false);
PoolList.RemoveAt(0);
}
}
}
}