Unity | Fixed startup scene when editor is running

1 Introduction

In the development process of multi-scene games, it is usually necessary to start the scenes in a specific order to complete some initialization work. So when we want to run an intermediate scene in the editor, we must first switch to the first scene. Such operations are not only cumbersome, but also affect development efficiency. Using the RuntimeInitializeOnLoadMethod property can help us load the specified scene when the editor is running, that is, the fixed startup scene

2 solutions

2.1 Function explanation

The RuntimeInitializeOnLoadMethod attribute allows "static" methods marked with this attribute to be automatically executed when the game starts . Its parameter type is RuntimeInitializeLoadType, which indicates the loading timing of the static method. The specific types are as follows:

The life cycle calling sequence corresponding to the loading timing is: BeforeSceneLoad –> Awake –> OnEnable –> AfterSceneLoad –> Start

For an introduction to functions and their parameters, please refer to the official documentation.

Function description: "https://docs.unity.cn/cn/2019.4/ScriptReference/RuntimeInitializeOnLoadMethodAttribute-ctor.html"

Parameter description: "https://docs.unity.cn/cn/2019.4/ScriptReference/RuntimeInitializeLoadType.html"

2.2 How to use

We need to load the specified scene when the game starts, so select the BeforeSceneLoad type. Then load the specified scene through SceneManager.LoadScene() in the function, so that every time it runs, it will jump from the current scene to the specified scene. This "static" method can be placed in any type of script file and will execute correctly whether inside or outside the Editor directory.

Of course, first make sure that the jump scene is in the Build Settings of the editor.

[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
private static void Initialize()
{
    SceneManager.LoadScene("SceneName");
}

3 expansion plans

The above method can ensure that when we start from any scene in the editor, we will jump to the specified scene. However, in addition to the formal scenarios during release, there will also be many test scenarios in the project. When running a test scene, you do not expect to jump to the first scene. You can use SceneManager.GetActiveScene() to obtain the current active scene and determine whether you need to jump to the first scene based on its name.

[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
private static void Initialize()
{
    Scene scene = SceneManager.GetActiveScene();
    if (!scene.name.Equals("SceneName"))
    {
        SceneManager.LoadScene("SceneName");
    }
}

For more source code, please scan the code to obtain

For more source code, please scan the code to obtain

Guess you like

Origin blog.csdn.net/u010799737/article/details/132086856
Recommended