Files
Convention-Unity-Demo/Assets/Scripts/Environment/PrefabRootObject.cs

89 lines
2.7 KiB
C#
Raw Normal View History

2025-12-15 17:59:27 +08:00
using Convention;
2025-12-15 17:20:55 +08:00
using Demo.Game.Attr;
2025-09-25 19:04:05 +08:00
using System.Collections;
using System.Collections.Generic;
2025-12-15 17:59:27 +08:00
using System.IO;
2025-09-25 19:04:05 +08:00
using UnityEngine;
namespace Demo.Game
{
2025-12-15 17:59:27 +08:00
namespace ConfigType
{
public class PrefabRootObjectConfig : ScriptLoadableConfig
{
private readonly Dictionary<string, List<string>> LoadedGameObjectNames = new();
public override void Deserialize(BinaryReader reader)
{
base.Deserialize(reader);
}
public override void Serialize(BinaryWriter writer)
{
base.Serialize(writer);
}
}
}
2025-12-12 15:19:10 +08:00
[Scriptable]
2025-09-25 19:04:05 +08:00
public class PrefabRootObject : ScriptableObject, IAssetBundleLoader
{
public static PrefabRootObject Make()
{
return new GameObject().AddComponent<PrefabRootObject>();
}
2025-12-15 17:59:27 +08:00
private int LoadingCounter = 0;
private readonly Dictionary<string, List<string>> LoadedGameObjectNames = new();
private readonly List<GameObject> LoadedGameObjects = new();
protected override IEnumerator DoSomethingDuringApplyScript()
{
yield return base.DoSomethingDuringApplyScript();
yield return new WaitUntil(() => LoadingCounter == 0);
}
2025-09-25 19:04:05 +08:00
public override IEnumerator UnloadScript()
{
yield return base.UnloadScript();
2025-12-15 17:59:27 +08:00
foreach (var obj in LoadedGameObjects)
2025-09-25 19:04:05 +08:00
{
2025-12-15 17:59:27 +08:00
Destroy(obj);
}
foreach (var item in LoadedGameObjectNames)
{
yield return this.UnloadAssetBundle(item.Key);
2025-09-25 19:04:05 +08:00
}
}
/// <summary>
/// 加载预制体作为子物体
/// </summary>
/// <param name="ab"></param>
/// <param name="prefab"></param>
[Convention.RScript.Variable.Attr.Method]
2025-12-15 17:59:27 +08:00
public void Load(string ab, string prefab)
2025-09-25 19:04:05 +08:00
{
2025-12-15 17:59:27 +08:00
LoadingCounter++;
ConventionUtility.StartCoroutine(this.LoadAssetBundle(ab, assetBundle =>
2025-09-25 19:04:05 +08:00
{
2025-12-15 17:59:27 +08:00
GameObject prefabObject = null;
if (assetBundle != null)
2025-09-25 19:04:05 +08:00
{
2025-12-15 17:59:27 +08:00
prefabObject = Instantiate(assetBundle.LoadAsset<GameObject>(prefab));
LoadedGameObjects.Add(prefabObject);
prefabObject.transform.SetParent(transform);
2025-12-15 17:59:27 +08:00
if (LoadedGameObjectNames.ContainsKey(ab) == false)
LoadedGameObjectNames.Add(ab, new());
LoadedGameObjectNames[ab].Add(prefab);
2025-09-25 19:04:05 +08:00
}
else
{
2025-12-15 17:59:27 +08:00
Debug.LogError($"Load AssetBundle failed", this);
2025-09-25 19:04:05 +08:00
}
2025-12-15 17:59:27 +08:00
LoadingCounter--;
}));
2025-09-25 19:04:05 +08:00
}
}
}