using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 对象池
/// </summary>
public class ObjectPool : MonoBehaviour
{
//使用单例模式
public static ObjectPool Instance;
public GameObject prafab;//被实例的对象
public GameObject parent;//父物体
private Queue<GameObject> pools = new Queue<GameObject>();//存放对象的池
private void Awake()
{
if (Instance != null)
{
Destroy(gameObject);
}
else
{
Instance = this;
}
}
void Start()
{
//从Resources中获取物体
prafab = Resources.Load<GameObject>("Black holes");
//设置父物体
parent = this.transform;
InitPool(10, prafab);
}
/// <summary>
/// 初始化对象池
/// </summary>
/// <param name="_count">数量</param>
/// <param name="obj">要被实例对象</param>
public void InitPool(int _count, GameObject obj)
{
for (int i = 0; i < _count; i++)
{
GameObject go = Instantiate(obj);//实例化对象
go.SetActive(false);//隐藏对象
go.transform.SetParent(parent);//设置父类
pools.Enqueue(go);//放入对象池
}
}
/// <summary>
/// 从对象池拿取对象
/// </summary>
/// <returns>对象</returns>
public GameObject GetObjectToPool()
{
//如果对象池还有对象
if (pools.Count > 0)
{
GameObject go = pools.Dequeue();//从对象池拿出对象
go.transform.SetParent(null);//清空父类
go.SetActive(true);//显示对象
return go;
}
//如果对象池里没有对象了
return null;
}
/// <summary>
/// 把对象放回对象池
/// </summary>
/// <param name="obj">要放回的对象</param>
public void BackToPool(GameObject obj)
{
obj.SetActive(false);//隐藏对象
obj.transform.position = Vector3.zero;//坐标清零
obj.transform.SetParent(parent);//设置父类
pools.Enqueue(obj);//放入对象池
}
}
对象池代码
最新推荐文章于 2024-08-12 16:04:25 发布