89 lines
2.7 KiB
C#
89 lines
2.7 KiB
C#
using Convention;
|
|
using Demo.Game.Attr;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using UnityEngine;
|
|
|
|
namespace Demo.Game
|
|
{
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
|
|
[Scriptable]
|
|
public class PrefabRootObject : ScriptableObject, IAssetBundleLoader
|
|
{
|
|
public static PrefabRootObject Make()
|
|
{
|
|
return new GameObject().AddComponent<PrefabRootObject>();
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
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--;
|
|
}));
|
|
}
|
|
}
|
|
}
|