对象池
一、创建脚本PoolManager
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PoolManager : MonoBehaviour
{
public static PoolManager instance;
[Header("对象池预制体")]
public GameObject Prefabs;
[Header("对象池中对象数量")]
public int objCount;
private List
private void Awake()
{
instance = this;
}
//存入对象池
public void SaveToObjectPool(GameObject go)
{
if (list.Count< objCount)//列表中数量小于对象池规定数量
{
list.Add(go);
}
else
{
Destroy(go);
}
}
//从对象池中取出
public GameObject GetFromObjectPool()
{
if (list.Count > 0)//如果列表中有对象
{
GameObject go = list[0];//获取列表中第一个对象
list.RemoveAt(0);//从列表中移除
return go;
}
return Instantiate(Prefabs);//列表中没对象生成对象
}
//清理对象池
public void Clear()
{
list.Clear();
}
}
二、创建脚本CharacterAction
public class CharacterAction : MonoBehaviour
{
private List
void Update()
{
if (Input.GetMouseButtonDown(0))
{
GameObject go = PoolManager.instance.GetFromObjectPool();//从对象池获取对象
go.transform.position += transform.forward * 2 * Time.deltaTime;
list.Add(go);//添加到临时列表
Debug.Log("添加对象" + go);
go.SetActive(true);//激活显示
}
if (Input.GetMouseButtonDown(1))
{
if (list.Count > 0)//列表有对象时
{
PoolManager.instance.SaveToObjectPool(list[0]);//列表第一个对象存入对象池
list[0].SetActive(false);//失活
list.RemoveAt(0);//移除对象
}
}
}
}