DESKTOP-DDTRVOR\asus 2bee2c42b6 Merge branch 'main' into TT
# Conflicts:
#	.gitignore
#	Blacksmith/Assets/Editor/StarkBuilderSetting.asset
#	Blacksmith/Assets/Editor/StarkBuilderSetting.asset.meta
#	Blacksmith/Assets/Script/GameSystem.cs
#	Blacksmith/Assets/Script/UI/ForgePanel.cs
#	Blacksmith/UserSettings/Layouts/default-2022.dwlt
#	Blacksmith/project.config.json
2024-12-23 15:25:21 +08:00

87 lines
2.8 KiB
C#
Raw Permalink 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;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PrefabPool : MonoBehaviour
{
public static PrefabPool ins;
private Dictionary<string, Queue<GameObject>> objDic;
private void Awake()
{
ins = this;
objDic = new Dictionary<string, Queue<GameObject>>();
}
public void LoadObj(string key,Action<GameObject> action)
{
//如果池中没有该游戏物体或者游戏物体的队列中已经没有剩余的游戏对象时。
//在这种情况下需要实例化一个新的物体,然后在判断是否需要在池中新加一个健值对还是直接放入队列中去
//然后把新生成的放入池中。
if (!objDic.ContainsKey(key)||objDic[key].Count==0) {
AssetBundleManager.ins.LoadAsset(key, (GameObject obj) =>
{
obj.name = key;
obj.SetActive(true);
action.Invoke(obj);
});
return;
}
var obj = objDic[key].Dequeue();
obj.SetActive(true);
action.Invoke(obj);
}
public void LoadObj(string key,int i,Action<GameObject,int> action)
{
//如果池中没有该游戏物体或者游戏物体的队列中已经没有剩余的游戏对象时。
//在这种情况下需要实例化一个新的物体,然后在判断是否需要在池中新加一个健值对还是直接放入队列中去
//然后把新生成的放入池中。
if (!objDic.ContainsKey(key)||objDic[key].Count==0) {
AssetBundleManager.ins.LoadAsset(key, (GameObject obj) =>
{
obj.name = key;
obj.SetActive(true);
action.Invoke(obj,i);
});
return;
}
var obj = objDic[key].Dequeue();
obj.SetActive(true);
action.Invoke(obj,i);
}
public void AddPond(string key,int num)
{
AssetBundleManager.ins.LoadAsset(key, (GameObject obj) =>
{
obj.name = key;
obj.SetActive(true);
for (int i = 0; i < num-1; i++)
{
var a = Instantiate(obj, transform);
a.name = key;
RecycleObj(a);
}
});
}
public void RecycleObj(GameObject obj)
{
//由于生成的预制体的name后面都会加上Clone所以我们需要将其去除
string name=obj.name;
//如果不存在该类的游戏物体就在对象池中加入,存在则直接加入
if (!objDic.ContainsKey(name)) {
objDic.Add(name, new Queue<GameObject>());
}
obj.transform.parent = transform;
objDic[name].Enqueue(obj);
obj.SetActive(false);//记得将放入的游戏物体的属性设置为false
}
}