using Convention; using Demo.Game.Attr; 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 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); } 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.Length + 1]; temp[0] = key; Array.Copy(value, 0, temp, 1, value.Length); BinarySerializeUtility.SerializeArray(writer, value.ToArray()); } base.Serialize(writer); } } } [Scriptable] public class PrefabRootObject : ScriptableObject, IAssetBundleLoader { public static PrefabRootObject Make() { return new GameObject().AddComponent(); } private int LoadingCounter = 0; private readonly Dictionary> LoadedGameObjectNames = new(); private readonly List 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); } } /// /// 加载预制体作为子物体 /// /// /// [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(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--; })); } } }