using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PoolData
{
public GameObject fatherObj;
public List<GameObject> poolList;
public PoolData(GameObject obj, GameObject poolObj)
{
fatherObj = new GameObject(obj.name);
fatherObj.transform.parent = poolObj.transform;
poolList = new List<GameObject>() { obj };
}
public void PushObj(GameObject obj)
{
obj.SetActive(false);
//存起来
poolList.Add(obj);
//设置父对象
obj.transform.parent = fatherObj.transform;
poolList = new List<GameObject>() { obj };
obj.transform.parent = fatherObj.transform;
obj.SetActive(false);
}
public GameObject GetObj()
{
GameObject obj = null;
//取出第一个
obj = poolList[0];
poolList.RemoveAt(0);
obj.SetActive(true);
obj.transform.parent = null;
return obj;
}
}
public class PoolManager
{
private static PoolManager instance;
public static PoolManager Instance
{
get
{
if (instance == null)
{
instance = new PoolManager();
}
return instance;
}
}
public Dictionary<string, PoolData> poolDic = new Dictionary<string, PoolData>();
private GameObject pool;
/// <summary>
/// 获取对象
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public GameObject GetObj(string name)
{
GameObject obj = null;
if (poolDic.ContainsKey(name) && poolDic[name].poolList.Count > 0)
{
//有东西
obj = poolDic[name].GetObj();
}
else
{
//没有东西
obj = GameObject.Instantiate(Resources.Load<GameObject>(name));
obj.name = name;
}
return obj;
}
/// <summary>
/// 还回对象
/// </summary>
/// <param name="name"></param>
/// <param name="obj"></param>
public void PushObj(string name, GameObject obj)
{
if (pool == null)
pool = new GameObject("#Pool#");
obj.transform.parent = pool.transform;
obj.SetActive(false);
if (poolDic.ContainsKey(name))
{
poolDic[name].PushObj(obj);
}
else
{
poolDic.Add(name,new PoolData(obj,obj));
}
}
/// <summary>
/// 清空缓冲池的方法,主要用于切换场景
/// </summary>
public void Clear()
{
poolDic.Clear();
pool = null;
}
}