Unity AddressablesLoad加载
using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UIFramework;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
public static class AddressablesLoad
{
//加载模式
public static async void LoadAndInstantiatePrefab(string key)
{
// 同步加载预制体资源
GameObject prefab = LoadPrefabSync(key);
// 如果预制体加载成功,将其作为子对象添加到当前游戏对象下if (prefab != null){Debug.Log("LoadAndInstantiatePrefabkey:" + key);实例化预制体到指定的位置Transform parent = UIRoot.Get<PanelC_Main>()._racemode;GameObject instance = Object.Instantiate(prefab, parent);Debug.Log("parent:" + parent.name);prefab.transform.localPosition = Vector3.zero; // 可以根据需要调整位置UIRoot.Get<PanelC_Main>().ShowHomePage(false);}
}
static GameObject LoadPrefabSync(string key)
{// 使用Addressables.LoadAssetAsync<GameObject>进行同步加载AsyncOperationHandle<GameObject> opHandle = Addressables.LoadAssetAsync<GameObject>(key);// 等待加载完成opHandle.WaitForCompletion();// 检查是否有错误发生if (opHandle.Status == AsyncOperationStatus.Succeeded){// 加载成功,返回预制体资源return opHandle.Result;}else{// 打印错误日志Debug.LogError($"Failed to load prefab with key: {key}. Error: {opHandle.OperationException}");return null;}
}
//卸载预制体资源 然后销毁预制体实例
public static void DestroyPrefab(string prefabKey)
{查找预制体实例并销毁Transform parent = UIRoot.Get<PanelC_Main>()._racemode;Debug.Log("parent:" + parent.name + "prefabKey:" + prefabKey);GameObject prefabInstance = parent.transform.Find(prefabKey + "(Clone)")?.gameObject;Debug.Log("DestroyPrefab:" + prefabInstance.name);if (prefabInstance != null){Object.Destroy(prefabInstance); // 销毁预制体实例}
}
}