Last Updated on 2021-11-03 by Clay
There are very few games have a scene from beginning to end. Even the oldest games generally have "starting interface" > "the first game level" > "the second game level"... such scene switching.
Today I want to record of how to switch the game scenes with program. The reason for switching scenes can be clicked on a specific button or character dead... These are determined by the different needs of each game.
Switch game scene
First, we need to check the game scenes are all add in the Scenes in Build. Go to the page through File > Build Settings... .
If there is a scene but not in the Scenes In Build, you can use Add Open Scenes button to add it. And then we can use the scene index to switch the scenes.
The code for switching scenes is as follows:
SceneManager.LoadScene(0);
The trigger time depends on the needs of the game. When the program reaches this line, it will automatically switch to scene 0.
Restart the game scene
There is a very common function that is recorded by the way: Restart the current game level. If the game character dead, we can let player challenge the game again. At this time we can use the following program to do it:
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
Then the game will be restarted.
References
- https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.html
- https://docs.unity3d.com/2018.1/Documentation/ScriptReference/SceneManagement.SceneManager.LoadScene.html
- https://docs.unity3d.com/ScriptReference/SceneManagement.Scene-name.html