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

66 lines
1.9 KiB
C#
Raw Normal View History

2025-09-25 19:04:05 +08:00
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Demo.Game
{
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();
2025-09-25 19:04:05 +08:00
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>
[ScriptableCall(@"
<summary>
</summary>
<param name=""ab""></param>
<param name=""prefab""></param>
")]
public IEnumerator Load(string ab, string prefab)
2025-09-25 19:04:05 +08:00
{
AssetBundle assetBundle = null;
yield return this.LoadAssetBundle(ab, x => assetBundle = x);
GameObject prefabObject = null;
if (assetBundle != null)
2025-09-25 19:04:05 +08:00
{
var ir = assetBundle.LoadAssetAsync<GameObject>(prefab);
yield return ir;
if (ir.asset != null)
2025-09-25 19:04:05 +08:00
{
prefabObject = Instantiate(ir.asset as GameObject);
Prefabs.Add(prefabObject);
prefabObject.transform.SetParent(transform);
AssetBundles.Add(ab);
2025-09-25 19:04:05 +08:00
}
else
{
Debug.LogError($"Load Prefab failed", this);
2025-09-25 19:04:05 +08:00
}
}
else
{
Debug.LogError($"Load AssetBundle failed", this);
}
2025-09-25 19:04:05 +08:00
}
}
}