Warm tip: This article is reproduced from serverfault.com, please click

EditorSceneManager using SceneManager in Play mode test

发布于 2020-12-02 09:33:28

I would need to use EditorSceneManager to load the scene for play mode unit test. I need to use this one and not SceneManager.Load since I cannot have the scene in Build settings. The documentation about EditorSceneManager is clear that it is supposed to do what I need.

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

I get error that the scene is not in the build settings as if SceneManager.LoadScene was called instead of the editor version.

Compiler also suggests to simplify to the following that I do not want to use:

 UnityEngine.SceneManagement.SceneManager.LoadScene(sceneName);

though I have no directives that could confuse the code:

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

I was using a side solution with IPrebuildSetup, IPostBuildCleanup to add/remove the scene via the AssetDatabase and EditorBuildSettingsScene and it works. But it also runs the scene loading/unloading process in Jenkins while building the prod app. I need to avoid that since it could lead to shipping assets that are only used in test scenes.

Questioner
fafase
Viewed
0
derHugo 2020-12-02 20:14:43

The EditorSceneManager inherits from SceneManager that's why it provides the same method LoadScene which afaik does the same thing, meaning there is no override or something like this for the EditorSceneManager.

However it provides additional methods you can and should use for editor specific stuff.

You can use 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);

Note: The parameter is called path, not sceneName, for a reason ;)

You have to provide the path as it is stored in Scene.path

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