using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public struct PoolObject
{
public GameObject gameObject;
public string type;
public bool isusing;
public PoolObject(GameObject gameObject,string type,bool isusing)
{
this.gameObject = gameObject;
this.type = type;
this.isusing = isusing;
}
}
public class EasyPool
{
private static EasyPool main;
public static EasyPool Main
{
get
{
main = main ?? new EasyPool();
return main;
}
}
private List<PoolObject> poolObjects = new List<PoolObject>();
private PoolObject pObject;
private GameObject pool;
public GameObject Instance(GameObject instance,string type)
{
for (int i = 0; i < poolObjects.Count; i++)
{
if (poolObjects[i].type == instance.name && poolObjects[i].isusing == false)
{
pObject = poolObjects[i];
pObject.isusing = true;
pObject.gameObject.SetActive(true);
pObject.gameObject.transform.position = instance.transform.position;
poolObjects[i] = pObject;
return poolObjects[i].gameObject;
}
}
if (pool == null)
{
pool = new GameObject();
pool.name = "pool";
}
GameObject gg = GameObject.Instantiate(instance);
gg.transform.parent = pool.transform;
gg.transform.position = instance.transform.position;
gg.SetActive(true);
poolObjects.Add(new PoolObject(gg,type,true));
return gg;
}
public void Close(GameObject des)
{
for (int i = 0; i < poolObjects.Count; i++)
{
if (poolObjects[i].gameObject.transform == des.transform && poolObjects[i].isusing)
{
pObject = poolObjects[i];
pObject.gameObject.transform.position = new Vector3(float.MaxValue,float.MaxValue,float.MaxValue);
pObject.gameObject.SetActive(false);
pObject.isusing = false;
poolObjects[i] = pObject;
}
}
}
public void Destroy(GameObject des)
{
for (int i = 0; i < poolObjects.Count; i++)
{
if (poolObjects[i].gameObject.transform == des.transform)
{
pObject = poolObjects[i];
GameObject.Destroy(pObject.gameObject);
poolObjects.RemoveAt(i);
return;
}
}
}
}
Unity学习笔记:自制的简单对象池
最新推荐文章于 2023-11-03 16:57:58 发布