using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool : MonoBehaviour {
public static ObjectPool _instance;
public Stack<GameObject> objects = new Stack<GameObject>();
private void Awake()
{
_instance = this;
}
public void Delete(GameObject g) //隐藏对象,入栈
{
g.SetActive(false);
objects.Push(g);
}
public GameObject Creat(GameObject prefab,Vector3 pos,Quaternion rot)
{
GameObject g = null;
if (objects.Count > 0)
{
g = objects.Pop();
g.SetActive(true);
g.transform.position = pos;
g.transform.rotation = rot;
}
else
{
g = Instantiate(prefab, pos, rot);
}
return g;
}
}
使用方法:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PoolTest : MonoBehaviour {
public GameObject Prefab;
public Stack<GameObject> s = new Stack<GameObject>();
public void Creat() //出栈
{
s.Push(ObjectPool._instance.Creat(Prefab, Vector3.zero, Quaternion.identity));
}
public void delete()
{
ObjectPool._instance.Delete(s.Pop());
}
}