Переход между сценами в Unity по кнопке + видео
В этом уроке мы затронем библиотеку Scene Management, чтобы сделать переход между сценами по кнопке. Это одна из самых простых вещей, но она необходима для создания игры.
Давайте начнем. Для начала создадим в ассетах 2 новые сцены и назовем их «Scene1» и «Scene2».



Чтобы создать новую сцену, щелкните правой кнопкой мыши по панели ассетов и выберите Create > Scene.
В этих сценах нам нужно создать элементы, с помощью которых мы будем переходить между сценами. Сделать это можно различными способами, но для облегчения понимания будем использовать самый простой способ. Мы будем создавать объект SceneChanger, который будет обрабатывать весь код изменения сцены.
Обычно, когда сцена сменяется от одной к другой, все экземпляры игровых объектов, сценариев и т. д., принадлежащие этой сцене, уничтожаются, а загружаются экземпляры из новой. Другой метод заключается в использовании функции DontDestroyOnLoad (), которая будет поддерживать ссылку на объект при смене сцены, но об этом следует поговорить в другом уроке.
Создание объекта и префаба SceneChanger
Итак, вернемся в Unity, на вкладке иерархии в «Scene1» создадим пустой объект и назовем его «SceneChanger».


Теперь добавим скрипт к объекту «SceneChanger» и назовем его «SceneChanger».
Откроем скрипт в Visual Studio и напишем следующий код:


Далее необходимо создать префаб , для этого просто выберите объект в иерархии и перетащите его в папку «Assets» на вкладке «Project» . После этого вы увидите синий куб с тем же именем объекта.



Теперь сохраните сцену и дважды щелкните «Scene2» . В этой сцене необходимо скопировать префаб SceneChanger. Для этого просто перенесем его во вкладку иерархии.
Создание пользовательского интерфейса
В пользовательском интерфейсе у нас будет текстовый объект с указанием названия сцены и кнопка, которая будет изменять сцену.
Итак, щелкните правой кнопкой мыши на вкладке Hierarchy и выберите UI> Panel .


Снова щелкните правой кнопкой мыши на вкладке Hierarchy и выберите UI> Text .
Еще раз щелкните правой кнопкой мыши на вкладке Hierarchy и выберите UI> Button .
Ваш конечный результат должен выглядеть примерно так



Изменим текст на «THIS IS SCENE 1» и текст в кнопке на «CHANGE SCENE». Результат выглядит следующим образом:

Далее необходимо выбрать объект Button в Иерархии. На вкладке инспектора нажмем значок «плюс» в компоненте «Button».





Перетащим объект SceneChanger из иерархии в ссылку на объект (выделено красным цветом)

Теперь нужно выбрать функцию (выделено красным). В раскрывающемся списке выберите SceneChanger> ChangeScene (string).
Теперь вы увидите пустое место под раскрывающимся списком функций. Введите в нем «Scene2». Здесь мы выбрали объект SceneChanger и получили доступ к функции ChangeScene (). «Scene2» является входом. Теперь при каждом нажатии кнопки вызывается функция ChangeScene (), и сцена меняется на «Scene2» .
Cделайте то же самое для «Scene2», но введите «Scene1» в качестве входа и измените текст в Scene2 соответствующим образом.
Сейчас нужно добавить сцены в Build Settings в File menu . Это необходимо, так как без этого Unity не распознает cцены, и между ними не произойдет никакого перехода.
Нажмите на кнопку воспроизведения. Нажатие на кнопку в сцене приведет к переходу к другой сцене.
Unity: Load scene on button press
A common task when building an application with Unity is to change to a different scene when the user is pushing a button. This is in itself a very easy task as Unity provides the SceneManager.LoadScene("MyScene"); method. Unfortunately, a lot of people end up having a lot of different scripts, with hard coded scene name strings in each of them essentially ending up with one script per button.
What I would like to share here is a very simple technique that allows creating just one generic script and assigning the scene to switch to in the inspector.
Step by step
- Create a new script named SceneLoader with the following content:
- In your scene, select the UI button element you want to use to change to a different scene to bring it up in the inspector.
- Add the SceneLoader.cs script as a script component to the button.
- Add a new entry to the On Click() list.
- In the new entry, drag the button object to the field showing None (Object) .
- Select the SceneLoader -> LoadScene function
- Add the name of the scene you want to load in the parameter field.
Make sure that you drag the button object onto the None (Object) field of the On Click() list entry and not the SceneLoader() script. See the Troubleshooting section below.
And that’s it. Now you have a way of loading a different scene upon a button click by using just the inspector and without having to create a separate script each time.
Here’s a screeshot of the relevant sections of the button inspector after completing the steps outline above:
Troubleshooting
The most common problem is that people tend to drag the script instead of the button object onto the None (Object) field of the entry in the On Click() list. In that case, the No Function dropdown will not list the SceneLoader.LoadScene() method:
This is a personal blog about things & stuff. Nothing on this website should be considered to be true or even accurate. Personal opinions may vary over time.
Set up multiple scenes
You can add multiple scenes, edit how you view them, and change the scene A Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary settings.
Add scenes
To add a new scene to your project, do one of the following:
- Right click to open the menu of a scene asset in the Project window A window that shows the contents of your Assets folder (Project tab) More info
See in Glossary and select Open Scene Additive. - Drag one or more scenes from the Project window into the Hierarchy window.
View scenes
The Hierarchy window displays all the scenes that are part of your project:
The Hierarchy window with multiple scenes added.
A: Scenes with unsaved changes have an asterisk by the scene name.
B: The scene More menu allows you to perform actions on the scene.
C: The scene divider (an inverted triangle) lets you collapse a scene and hide its contents from the Hierarchy to better manage multiple scenes.
Tip: To add a scene to the Hierarchy window without loading it, press Alt (macOS: press Option) and drag the scene into the Hierarchy window. This lets you load the scene when it’s convenient for you.
Loaded scene More menu (⋮)
You can interact with and edit a loaded scene in several ways.
The More menu for a loaded scene.
| Setting | Description |
|---|---|
| Set Active Scene | Sets the scene as the target for new GameObjects The fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject’s functionality is defined by the Components attached to it. More info See in Glossary created through scripts A piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info See in Glossary . For more information, see SceneManager.SetActiveScene. |
| Save Scene | Saves the scene that you selected. |
| Save Scene As | Opens your file browser so you can choose where and how to save the scene. |
| Save All | Saves all the scenes you have open in the Hierarchy window. |
| Unload Scene | Hides the contents of the scene from the Scene view An interactive view into the world you are creating. You use the Scene View to select and position scenery, characters, cameras, lights, and all other types of Game Object. More info See in Glossary and the Hierarchy window. If you have unsaved changes, save them before you unload the scene to not lose any changes. |
| Remove Scene | Removes the scene from the Hierarchy window. |
| Discard changes | Undoes any changes that you haven’t saved. |
| Select Scene Asset | Highlights the scene asset in the Project window. |
| Add New Scene | Adds a new untitled scene below the scene you have selected. |
| GameObject | Opens a dropdown menu of GameObjects that you can add to the scene you have selected. |
Unloaded scene More menu (⋮)
You can interact with and edit an unloaded scene in fewer ways than you can a loaded scene.
The More menu for an unloaded scene.
| Setting | Description |
|---|---|
| Load Scene | Displays the contents of the scene in the Hierarchy window and the Scene view, and allows you to edit them. |
| Remove Scene | Removes the scene from the Hierarchy window. |
| Select Scene Asset | Highlights the scene asset in the Project window. |
| Add New Scene | Adds a new untitled scene below the scene you have selected. |
Multiple scenes in Play mode
When you are in Play mode and have multiple scenes in the Hierarchy window, the Editor displays an additional scene called DontDestroyOnLoad. You can’t access the DontDestroyOnLoad scene and it’s also not available at runtime.
Scene-specific settings
The following settings are specific to each scene:
- RenderSettings and LightmapSettings (both found in the Lighting window).
- NavMesh A mesh that Unity generates to approximate the walkable areas and obstacles in your environment for path finding and AI-controlled navigation. More info
See in Glossary settings. - Scene settings in the Occlusion Culling A that disables rendering of objects when they are not currently seen by the camera because they are obscured (occluded) by other objects. More info
See in Glossary window.
Each scene manages its own settings, so only settings associated with that scene save to the scene file.
To change the settings of a specific scene, either open that specific scene and change the settings, or set the scene as the active scene then change the settings. Otherwise, if you have multiple scenes open, Unity uses the rendering and NavMesh settings from the active scene.
When you switch to a new active scene in the Editor or at runtime, Unity replaces all previous settings with the settings from the new active scene.
Unity | Переход между сценами
Переход между сценами в Unity осуществляется довольно просто:
Как заменить начальную сцену
Довольно часто возникает необходимость сменить сцену, открываемую при запуске игры. Сделать это довольно просто:

При запуске игры открывается самая первая сцена в списке “Scenes In Build”. Достаточно перетащить в начало другую и она будет запускаться первой.
Если же нужной сцены нет в списке, а она открыта у вас в редакторе, то просто нажмите на кнопку: