134 lines
3.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
/// <summary>
/// 池子里的一列容器
/// </summary>
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>() { obj };
PushObj(obj);
}
/// <summary>
/// 往容器里面压东西
/// </summary>
/// <param name="obj"></param>
public void PushObj(GameObject obj)
{
//失活隐藏
obj.SetActive(false);
//存起来
poolList.Add(obj);
//设置父对象
obj.transform.parent = fatherObj.transform;
}
/// <summary>
/// 从容器里面取东西
/// </summary>
/// <returns></returns>
public GameObject GetObj()
{
GameObject obj = null;
//取出第一个
obj = poolList[0];
poolList.RemoveAt(0);
//激活显示
obj.SetActive(true);
//断开父对象
obj.transform.parent = null;
return obj;
}
}
//缓存池模块,对象池
//Dictionary List 字典 链表
//GameObject和Resources两个公共类的API
public class PoolMgr :BaseManager<PoolMgr>
{
//缓存池容器
public Dictionary<string,poolData> poolDic = new Dictionary<string, poolData>();
private GameObject poolObj;
/// <summary>
/// 往外拿东西
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public void GetObj(string name,UnityAction<GameObject> callback)
{
//GameObject obj = null;
//有容器,且容器有物品,可以拿
if(poolDic.ContainsKey(name) && poolDic[name].poolList.Count > 0)
{
//obj = poolDic[name].GetObj();
callback(poolDic[name].GetObj());
}
else
{
//将下面的改成异步加载资源,创建对象给外部用
ResMgr.GetInstance().LoadAsync<GameObject>(name, (o) =>
{
o.name = name;
callback(o);
});
// obj = GameObject.Instantiate(Resources.Load<GameObject>(name));
//把对面名字改得和池子的名字一样
// obj.name = name;
}
}
/// <summary>
/// 还回去
/// </summary>
public void PushObj(string name, GameObject obj)
{
if (poolObj == null)
{
poolObj = new GameObject("Pool");
}
//里面有容器
if (poolDic.ContainsKey(name))
{
poolDic[name].PushObj(obj);
}
//里面没有容器
else
{
//加一个list直接加个物品进去
poolDic.Add(name, new poolData(obj,poolObj));
}
}
/// <summary>
/// 清空缓存池,主要用在场景切换时
/// </summary>
public void Clear()
{
poolDic.Clear();
poolObj = null;
}
}