단순 대상 캐시 실현
10782 단어 unity
https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
private Dictionary<System.Type, List<GameObject>> dicpool = new Dictionary<System.Type, List<GameObject>>();
public int Objmaxcount;
//
private static pool instance;
public static pool Instance
{
get
{
if (instance == null)
instance = new pool();
return instance;
}
}
void Awake()
{
DontDestroyOnLoad(gameObject);
instance = this;
}
public GameObject CreateObject(GameObject obj)
{
List<GameObject> tmplist = new List<GameObject>();
if (dicpool.ContainsKey(obj.GetType()) && dicpool[obj.GetType()].Count > 0)
{
tmplist = dicpool[obj.GetType()];
tmplist[0].SetActive(true);
GameObject go = tmplist[0];
tmplist.Remove(go);
return go;
}
for (int i = 0; i < Objmaxcount; i++)
{
GameObject go = Instantiate(obj);
go.SetActive(false);
tmplist.Add(go);
}
dicpool.Add(obj.GetType(), tmplist);
return Instantiate(obj);
}
public void DestroyObject(GameObject obj)
{
if (dicpool.ContainsKey(obj.GetType()))
{
List<GameObject> tmplist = dicpool[obj.GetType()];
if (tmplist.Count >= Objmaxcount)
{
Destroy(obj);
return;
}
tmplist.Add(obj);
obj.SetActive(false);
}
else
{
Destroy(obj);
}
}