Files
Convention-Unity-Demo/Assets/Scripts/Environment/PrefabRootObject.cs
2025-12-12 15:19:10 +08:00

62 lines
1.8 KiB
C#

using Demo.Attr;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Demo.Game
{
[Scriptable]
public class PrefabRootObject : ScriptableObject, IAssetBundleLoader
{
public static PrefabRootObject Make()
{
return new GameObject().AddComponent<PrefabRootObject>();
}
private readonly List<string> AssetBundles = new();
private readonly List<GameObject> Prefabs = new();
public override IEnumerator UnloadScript()
{
yield return base.UnloadScript();
foreach (var ab in AssetBundles)
{
yield return this.UnloadAssetBundle(ab);
}
}
/// <summary>
/// 加载预制体作为子物体
/// </summary>
/// <param name="ab"></param>
/// <param name="prefab"></param>
[Convention.RScript.Variable.Attr.Method]
public IEnumerator Load(string ab, string prefab)
{
AssetBundle assetBundle = null;
yield return this.LoadAssetBundle(ab, x => assetBundle = x);
GameObject prefabObject = null;
if (assetBundle != null)
{
var ir = assetBundle.LoadAssetAsync<GameObject>(prefab);
yield return ir;
if (ir.asset != null)
{
prefabObject = Instantiate(ir.asset as GameObject);
Prefabs.Add(prefabObject);
prefabObject.transform.SetParent(transform);
AssetBundles.Add(ab);
}
else
{
Debug.LogError($"Load Prefab failed", this);
}
}
else
{
Debug.LogError($"Load AssetBundle failed", this);
}
}
}
}