Play模式测试中使用SceneManager的EditorSceneManager

EditorSceneManager using SceneManager in Play mode test

我需要使用 EditorSceneManager 加载场景以进行播放模式单元测试。 我需要使用这个而不是 SceneManager.Load,因为我无法在构建设置中使用场景。关于 EditorSceneManager 的文档很清楚,它应该做我需要的。

    protected void LoadScene(string sceneName, Action onComplete)
    {
        if (string.IsNullOrEmpty(sceneName)) { Debug.LogError("Missing scene name"); return;}
        UnityEditor.SceneManagement.EditorSceneManager.LoadScene(sceneName);
        //...
    }

我收到错误消息,场景不在构建设置中,就好像 SceneManager.Load调用的是场景而不是编辑器版本。

编译器还建议简化为我不想使用的以下内容:

 UnityEngine.SceneManagement.SceneManager.LoadScene(sceneName);

尽管我没有可能混淆代码的指令:

using System;
using System.Collections;
using UnityEditor;
using UnityEngine;

我通过 AssetDatabase 和 EditorBuildSettingsScene 使用带有 IPrebuildSetup、IPostBuildCleanup 的辅助解决方案 add/remove 场景并且它有效。但它还在 Jenkins 中运行 scene loading/unloading 进程,同时构建 prod 应用程序。我需要避免这种情况,因为它可能导致运送仅用于测试场景的资产。

你应该写一个

using UnityEngine.SceneManagement;

然后你可以用

加载场景
SceneManager.LoadScene(sceneName);

这样应该就可以了

EditorSceneManager 继承自 SceneManager 这就是为什么它提供了相同的方法 LoadScene 而 afaik 做同样的事情,这意味着 [= 没有覆盖或类似的东西11=].

但是它提供了您可以并且应该用于编辑器特定内容的其他方法。

您可以使用LoadSceneInPlayMode

This method allows you to load a Scene during playmode in the editor, without requiring the Scene to be included in the Build Settings Scene list.

UnityEditor.SceneManagement.EditorSceneManager.LoadSceneInPlayMode(sceneName);

注意:参数被称为path,而不是sceneName,这是有原因的;)

您必须提供存储在 Scene.path

中的路径

Returns the relative path of the Scene. Like: "Assets/MyScenes/MyScene.unity"