Files
2025-12-19 15:54:51 +08:00

111 lines
3.7 KiB
C#

using Convention;
using Demo.Game.Attr;
using Demo.Game.ConfigType;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
namespace Demo.Game
{
namespace ConfigType
{
public class PrefabRootObjectConfig : ScriptLoadableConfig
{
public Dictionary<string, List<string>> LoadedGameObjectNames = new();
public override void Deserialize(BinaryReader reader)
{
int count = BinarySerializeUtility.ReadInt(reader);
for (; count > 0;count--)
{
var temp = BinarySerializeUtility.DeserializeStringArray(reader);
var key = temp[0];
var value = temp[1..];
LoadedGameObjectNames.Add(key, value.ToList());
}
base.Deserialize(reader);
}
public override void Serialize(BinaryWriter writer)
{
BinarySerializeUtility.WriteInt(writer, LoadedGameObjectNames.Count);
foreach (var (key,value) in LoadedGameObjectNames)
{
string[] temp = new string[value.Count + 1];
temp[0] = key;
for(int i=0,e=value.Count;i<e;i++)
{
temp[1 + i] = value[i];
}
BinarySerializeUtility.SerializeArray(writer, value.ToArray());
}
base.Serialize(writer);
}
}
}
[Scriptable]
public class PrefabRootObject : ScriptableObject, IAssetBundleLoader
{
public static PrefabRootObject Make()
{
return new GameObject().AddComponent<PrefabRootObject>();
}
private int LoadingCounter = 0;
private Dictionary<string, List<string>> LoadedGameObjectNames => GetConfig<PrefabRootObjectConfig>().LoadedGameObjectNames;
private readonly List<GameObject> LoadedGameObjects = new();
protected override IEnumerator DoSomethingDuringApplyScript()
{
yield return base.DoSomethingDuringApplyScript();
yield return new WaitUntil(() => LoadingCounter == 0);
}
public override IEnumerator UnloadScript()
{
yield return base.UnloadScript();
foreach (var obj in LoadedGameObjects)
{
Destroy(obj);
}
foreach (var item in LoadedGameObjectNames)
{
yield return this.UnloadAssetBundle(item.Key);
}
}
/// <summary>
/// 加载预制体作为子物体
/// </summary>
/// <param name="ab"></param>
/// <param name="prefab"></param>
[Convention.RScript.Variable.Attr.Method]
public void Load(string ab, string prefab)
{
LoadingCounter++;
ConventionUtility.StartCoroutine(this.LoadAssetBundle(ab, assetBundle =>
{
GameObject prefabObject = null;
if (assetBundle != null)
{
prefabObject = Instantiate(assetBundle.LoadAsset<GameObject>(prefab));
LoadedGameObjects.Add(prefabObject);
prefabObject.transform.SetParent(transform);
if (LoadedGameObjectNames.ContainsKey(ab) == false)
LoadedGameObjectNames.Add(ab, new());
LoadedGameObjectNames[ab].Add(prefab);
}
else
{
Debug.LogError($"Load AssetBundle failed", this);
}
LoadingCounter--;
}));
}
}
}