关闭场景时有些对象没有清理干净

Some objects were not cleaned up when closing the scene

场景加载时控制台中出现此错误:

Some objects were not cleaned up when closing the scene. (Did you spawn new GameObjects from OnDestroy?)

我知道这是因为我 Instantiate 一个对象在 OnDestroy 方法中,我知道 how to fix 这个问题在应用程序退出时出现。但我不知道如何通过 SceneManager.LoadScene()

在场景更改时解决此问题

有什么方法可以满足这个需求吗,比如OnSceneUnload

您可以像这样使用OnLevelWasLoaded(int level)

    void OnLevelWasLoaded(int level)
    {
        if (Application.loadedLevelName == "MyNextScene") 
        {
            // Clean Up leaked objects
        }
    }

场景变化时调用

更新:

上面的建议是创建在加载新场景时不清理的脚本,所以基本上你需要在这个脚本中使用这样的东西:

void Awake() 
{
    DontDestroyOnLoad(this.gameObject);
}

然后将这些未清理的对象存储在该脚本的某个集合中,并让它在场景更改时为您清理。

我在 OnDisable 中实例化对象时遇到了类似的问题。

对我有用的是检查场景是否仍在 OnDisable 中加载。这在退出 app/editor 和卸载场景时都返回 false。

void OnDisable()
{
        if(!this.gameObject.scene.isLoaded) return;
       // Instantiate objects here
}