PoolManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class PoolData
{
//抽屉中的父对象
public GameObject fatherObj;
//对象中的容器
public List<GameObject> poolList;
public PoolData(GameObject obj,GameObject poolObj)
{
//给我们的抽屉 创建父对象 并且把他作为我们pool衣柜对象的子物体
fatherObj = new GameObject(obj.name);
fatherObj.transform.parent = poolObj.transform;
poolList = new List<GameObject>() { };
PushObj(obj);
}
//往抽屉里压东西
public void PushObj(GameObject obj)
{
obj.SetActive(false);//失活 让其隐藏
poolList.Add(obj);//存起来
obj.transform.parent = fatherObj.transform;//设置父对象
}
//往抽屉里取东西
public GameObject GetObj()
{
GameObject obj = null;
//取出第一个
obj = poolList[0];
poolList.RemoveAt(0);
obj.SetActive(true);//激活让其显示
obj.transform.parent = null;//断开父子关系
return obj;
}
}
public class PoolManager : BaseManager<PoolManager>
{
public Dictionary<string, PoolData> poolDict = new Dictionary<string, PoolData>();
public GameObject poolObj;
/// <summary>
/// 拿东西,出
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public void GetObj(string name,UnityAction<GameObject> callback = null)
{
//有物
if(poolDict.ContainsKey(name) && poolDict[name].poolList.Count > 0)
{
callback(poolDict[name].GetObj());
}
//无物
else
{
//旧,同步加载
//obj = GameObject.Instantiate(Resources.Load<GameObject>(name));//新加载物体
//obj.name = name;
//新,异步加载
ResourcesManager.GetInstance().LoadAsync<GameObject>(name, (o) =>
{
o.name = name;
callback(o);
});
}
}
/// <summary>
/// 放东西,入
/// </summary>
/// <param name="name"></param>
/// <param name="obj"></param>
public void PushObj(string name, GameObject obj)
{
//物体归类,同物体到同文件夹
if (poolObj == null)
poolObj = new GameObject("pool");
//有类型
if (poolDict.ContainsKey(name))
{
poolDict[name].PushObj(obj);
}
//无类型,新增类型
else
{
poolDict.Add(name, new PoolData(obj,poolObj));
}
}
/// <summary>
/// 过场景的时候清空
/// </summary>
public void Clear()
{
poolDict.Clear();
poolObj = null;
}
}