返回

避免丢失实例化结果:Unity加载Addressable包返回成功,实例化不为空但场景中看不见物体的原因解析

前端

在使用Unity的Addressable加载包时,您可能会遇到这样的情况:加载包成功,InstantiateAsync能够执行,没有报错,能够返回Succeeded,并且如果打印handle.Result到控制台上,也能显示这个物体的名字,但是当您运行游戏时,却看不到实例化结果。这可能是因为实例化到了即将被删除的场景。

Unity的场景管理系统允许您在游戏中动态加载和卸载场景。当您加载一个新的场景时,旧的场景将被卸载。如果在旧场景中实例化的对象在卸载前没有被销毁,那么这些对象将被丢失。

要避免这种问题,您需要确保在卸载场景之前销毁所有在该场景中实例化的对象。您可以通过以下两种方式来实现:

  • 在脚本中手动销毁对象。
  • 使用Addressables的ReleaseInstance()方法来释放实例化的对象。

以下是使用Addressables的ReleaseInstance()方法来释放实例化的对象的示例:

using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;

public class ExampleScript : MonoBehaviour
{
    private AsyncOperationHandle<GameObject> handle;

    private void Start()
    {
        // Load the Addressable asset.
        handle = Addressables.InstantiateAsync("MyAsset");

        // Release the instance when the scene is unloaded.
        SceneManager.sceneUnloaded += OnSceneUnloaded;
    }

    private void OnSceneUnloaded(Scene scene)
    {
        // Check if the scene that is being unloaded is the same as the scene that the object was instantiated in.
        if (scene.name == SceneManager.GetActiveScene().name)
        {
            // Release the instance.
            Addressables.ReleaseInstance(handle);
        }
    }
}

通过使用上述方法,您可以确保在卸载场景之前销毁所有在该场景中实例化的对象,从而避免丢失实例化结果。