Как перейти на другую сцену в unity
Перейти к содержимому

Как перейти на другую сцену в unity

  • автор:

SceneManager.LoadScene

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Declaration

Declaration

Parameters

sceneName Name or path of the Scene to load.
sceneBuildIndex Index of the Scene in the Build Settings to load.
mode Allows you to specify whether or not to load the Scene additively. See LoadSceneMode for more information about the options.

Description

Loads the Scene by its name or index in Build Settings.

Note: In most cases, to avoid pauses or performance hiccups while loading, you should use the asynchronous version of this command which is: LoadSceneAsync.

When using SceneManager.LoadScene, the scene loads in the next frame, that is it does not load immediately. This semi-asynchronous behavior can cause frame stuttering and can be confusing because load does not complete immediately.

Because loading is set to complete in the next rendered frame, calling SceneManager.LoadScene forces all previous AsyncOperations to complete, even if AsyncOperation.allowSceneActivation is set to false. To avoid this, use LoadSceneAsync instead.

The given sceneName can either be the Scene name only, without the .unity extension, or the path as shown in the BuildSettings window still without the .unity extension. If only the Scene name is given this will load the first Scene in the list that matches. If you have multiple Scenes with the same name but different paths, you should use the full path.

Note that sceneName is case insensitive, except when you load the Scene from an AssetBundle.

For opening Scenes in the Editor see EditorSceneManager.OpenScene. SceneA can additively load SceneB multiple times. The regular name is used for each loaded scene. If SceneA loads SceneB ten times each SceneB will have the same name. Finding a particular added scene is not possible.

If a single mode scene is loaded, Unity calls Resources.UnloadUnusedAssets automatically.

The following two script examples show how LoadScene can load Scenes from Build Settings. LoadSceneA uses the name of the Scene to load. LoadSceneB uses the number of the Scene to load. The scripts work together.

Introduction

Switching between scenes is a basic task you want to achieve when developing your game in Unity. Here’s how to do so.

Prerequisites

  1. Unity game project (either 2D or 3D is fine)
  2. Two scenes: the tutorial below will guide you in creating the scenes
  3. Basic knowledge of C# programming

Steps

In this tutorial, I will teach you how to navigate from a Title Scene to a Game Scene. In the Title Scene, there will be a “Start Game” button. After the player pressed the button, it will navigate to Game Scene.

Step 1: Create a project / Launch your project

Step 2: (optional) change your scene name to TitleScene

To change the scene name, locate your Scene file in Project panel (by default it’s in the Scenes folder). Right-click and choose Rename. You will be asked whether you want to reload the scene, select Reload.

Step 2: Create a User Interface (UI) element: Button

To create a “Start Game” button, add a UI button Game object via Unity menu > GameObject > UI > Button.

After adding the button, there will be a few new elements appearing in the Hierarchy panel, including Canvas , Button and EventSystem . Do not remove them.

The Scene panel is now confusing, as the Button is huge, compared with the original camera area. If you zoom out in the Scene panel, it will look like this:

The big rectangle is the Canvas, which is the area for displaying the user interface elements. To make the Canvas size aligned with the camera, we can change the settings of the Canvas via the Inspector panel.

Select Canvas in the Hierarchy window, then in the Inspector panel > Canvas > Render Mode, choose “Screen Space -Camera”, and select the Render Camera as “Main Camera” in the scene. As a result, the Scene panel will become:

Step 3: (optional) Resize and Move button to a better position

The button is now at the lower right corner, which is undesirable. We shall move it to the centre of the scene. The text of the button can be edited via the Text GameObject under the Button in the Hierarchy window.

Optionally you can add your game title as a GameObject > UI > Text.

Once finished updating the UI elements, hit the Play button to start the game. It will look like this:

Click again the Play button to stop the Play mode.

Remember to save the changes.

Step 4: Create another Scene, named GameScene

To create a new scene, go to Unity menu > File > New Scene. Save the Scene as “GameScene” and save it in the Scenes folder.

In the newly created GameScene, create a text UI element to indicate it’s the game scene (remember to change the Render Mode of Canvas):

Save the changes.

Step 5: Create the button action in TitleScene

Go back to TitleScene, select the Main Camera. In the Inspector panel, select “Add Component” and create a new C# script named TitleSceneController .(note the capital letters and no space please). Double click the script to launch Visual Studio editor (in the older versions, Mono Editor will be launched instead).

The script will look like this by default:

We will first add a line around line 4, to add a required namespace to the script:

Then, we will add a piece of code before the last closing curly bracket:

The completed code is as follow (the codes highlighted in bold are newly added):

We added a function called ClickStart() , which is used to tell the button what to do when the “Press Start” button is clicked.

Step 6: Assign the function to the Start button

Back to Unity editor, select the Button. In the Inspector panel, there is an On Click section. Click the “+” sign and select the Main Camera in scene as the object. Then in the No Function pull down menu, select TitleSceneController > ClickStart().

Save the changes.

Step 7: Configure Build Settings to add all related scenes

Go to Unity menu > File > Build Settings, we drag all the scenes from the Scenes folder in Project panel to the upper part of the Build Settings dialog.

Close the Build Settings dialog afterwards.

If you have more than two scenes, make sure you add all of them into the Build Settings dialog.

Done!

From this point, the game is ready. Click Play button and try to click the “Start Game” button. It will redirect to Game Scene.

If you encounter any questions, please leave a comment below. I’ll be happy to help.

Переход между сценами

Приветствую! В данной статье мы разберём несколько способов перехода между сценами, а именно:

  1. Смена сцен по названию.
  2. Смена сцен по индексам.
  3. Смена сцен, используя параметры.

Смена сцен по названию

Данный способ самый простой, и встречается он очень часто. Он используется тогда, когда нам необходимо перейти точно на определённую сцену. Для этого создадим C# скрипт, с названием, например, Scenes. И пропишем в нём следующий код:

Разбор кода

Обратите внимание, что при работе со сценами, нам необходимо обязательно подключить библиотеку:

Дальше мы создаём функцию OpenMenu(), которая будет загружать сцену с названием Menu. Вторая функция с названием OpenGame() загружаем сцену с названием Game. Убедитесь, что сцены с такими названиями существуют в Вашем проекте.

Как видите, всё очень просто. Условия, при которых Вы будете запускать данные функции, могут быть совсем разные. Например: клик на клавишу «Esc», здоровье персонажа меньше нуля, и тд. Пример:

Смена сцен по индексам

Данный способ аналогичен предыдущему, за исключением того, что мы вместо названий сцен, используем их индексы. Данный способ полезен в тех случаях, когда нам необходимо перейти на следующую или предыдущую сцену. Создадим C# скрипт, с названием, например, Scenes. И пропишем в нём следующий код:

Как видите, код аналогичен предыдущему, поэтому разбирать мы его не будем. Единственное что хотелось бы отметить, что благодаря функциям, у нас открываются чуть больше возможностей перехода на сцены. Например, мы можем перейти на следующую или предыдущую функцию:

Разбор кода

Строчки в функции NextLevel():

В первой строчке мы в переменную index мы заносим тот индекс сцены, в котором мы находимся в данный момент. А уже во второй строчке, мы увеличиваем индекс нашей сцены на единицу, и запускаем таким образом следующую сцену.

В функции PreviousLevel() всё аналогично, только индекс мы не увеличиваем на единицу, а уменьшаем. Тем самым запускаем предыдущую сцену.

Обратите внимание! Перед тем как работать со сценами по их индексам, нам необходимо добавить все сцены в Build Settings. Для этого жмём на вкладку File — Build Settings. Далее перетаскиваем все свои сцены в область Scenes in Build, и расставляем их по порядку. После чего просто закрываем данное окно. Теперь можно спокойно работать с индексами.

Смена сцен, используя параметры

Данный способ аналогичен предыдущему, только здесь мы переходим на определённую сцену исходя из переданного аргумента в нашу функцию.

Разбор кода

Функция GoToLevel() принимает в качестве аргумента номер индекса, который нам необходимо открыть, и заносит его в переменную number. Этот метод защитит нас от дублирования однотипных функций, которые по идее выполняют одно и тоже.

Давайте теперь попробуем выполнить функцию GoToLevel(), передав ей аргумент «1» следующим образом:

Конечно же, в качестве аргумента мы можем передать не только индекс, но и название. Поэтому используя открытие сцены через аргумент функции, Вы можете работать как с индексами, так и с названиями сцен.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *