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); // 销毁预制体实例
    }
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值