Unity C#实现缓存池 优化性能
具体实现代码
// An highlighted block
public class Pool : Single<Pool> {
//缓存池父节点
private GameObject fatherPoint;
//记录所有池子的字典
Dictionary<string, Stack<GameObject>> allPool = new Dictionary<string, Stack<GameObject>>();
//Resources文件夹下对应资源文件夹绝对路径
private string localStr;
//存储资源名字
private List<string> prefabStr;
//存储 名字对应资源预制体
private Dictionary<string, Object> perfabDic;
protected override void Awake()
{
base.Awake();
fatherPoint = GameObject.Find("Pool");
localStr = @"D:\zwt\facebookDemo\Assets\Resources";
prefabStr = new List<string>();
perfabDic = new Dictionary<string, Object>();
this.GetResName();
this.LoadRes();
}
//获取资源名
private void GetResName()
{
DirectoryInfo folder = new DirectoryInfo(localStr);
//
foreach (FileInfo file in folder.GetFiles("*.prefab"))
{
string fileName = this.CancelBackName(file.Name);
prefabStr.Add(fileName);
}
}
//消除文件名后缀
private string CancelBackName(string name) {
string newStr="";
for (int i = 0; i < name.Length; i++)
{
//读到.号就退出 不要它的后缀名
if (name[i] == '.') {
break;
}
newStr += name[i];
}
return newStr;
}
//加载所有资源
private void LoadRes() {
for (int i = 0; i < prefabStr.Count; i++)
{
Object obj= Resources.Load(prefabStr[i]);
perfabDic.Add(prefabStr[i],obj);
}
}
//放入缓存池
public void Put(string key,GameObject obj) {
//判断pool中是否有对应键key
//有的话就直接放入对应字典
if (allPool.ContainsKey(key)) {
allPool[key].Push(obj);
}
else
{
Stack<GameObject> newPool = new Stack<GameObject>();
allPool.Add(key, newPool);
newPool.Push(obj);
}
obj.transform.parent = fatherPoint.transform;
obj.SetActive(false);
}
//从缓存池中取出 *prefab是模板 *position是取出位置 *rotation是克隆方向
public GameObject Get(string key,Vector3 position,Quaternion rotation)
{
判断池子中有无对应的key 并且对应key的池子中有对象
if (allPool.ContainsKey(key) && allPool[key].Count>0) {
GameObject targetObj = allPool[key].Pop();
targetObj.transform.position = position;
targetObj.transform.rotation = rotation;
targetObj.transform.parent = null;
targetObj.SetActive(true);
return targetObj;
}
else {
//不满足条件则自己克隆
GameObject targetObj = GameObject.Instantiate((GameObject)perfabDic[key], position, rotation);
return targetObj;
}
}
}
.