Как сделать рестарт уровня в unity
Перейти к содержимому

Как сделать рестарт уровня в unity

  • автор:

Scene Reloading

By default, 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 Reloading is enabled. This means that when you enter Play Mode, Unity destroys all existing Scene 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 and reloads the Scene from disk. The time it takes for Unity to do this increases with the complexity of the Scene, which means that as your project gets more complex, you have to wait longer between the moment you press the Play button and the moment the Scene fully loads in the Editor.

When you disable Scene Reloading, the process takes less time. This allows you to more rapidly iterate on the development of your project. Instead of reloading the Scene from disk, Unity only resets the Scene’s modified contents. This avoids the time and performance impact of unloading and reloading the Scene. Unity still calls the same initialization functions (such as OnEnable , OnDisable and OnDestroy ) as if it were freshly loaded.

Effects of skipping Scene Reload

To disable Scene Reloading:

  1. Go to Edit > Project Settings > Editor
  2. Make sure Enter Play Mode Options is enabled.
  3. Disable Reload Scene

When you disable Scene Reloading, the time it takes to start your application in the Editor is no longer representative of the startup time in the built version. Therefore, if you want to debug or profile exactly what happens during your project’s startup, you should enable Scene Reloading to more accurately represent the true loading time and processes that happen in the built version of your application.

Disabling Scene Reload should have minimal side effects on your project. However, because Scene Reloading is tightly connected to Domain Reload, there are a couple of important differences:

ScriptableObject and MonoBehaviour fields that are not serialized into the build ( [NonSerialized] , private, or internal) keep their values. This is because Unity does not recreate existing objects and does not call constructors. Additionally, Unity converts null private and internal fields of array/List type to an empty array/List object during Domain Reload and stay non-null for runtime (non-Editor) 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 .

Как сделать перезагрузку сцены

Всем привет. В данной статье мы научимся осуществлять перезагрузку текущей сцены. И для начала используя окно Hierarchy, добавим кнопку с надписью "Рестарт", которая как раз и будет перезагружать нашу сцену. Размер кнопки, текст, и изображение для кнопки отредактируйте сами, на Ваш вкус.

Далее создадим скрипт C#, с названием Scenes, со следующим содержимым:

Здесь мы создали метод ReastartLevel(), при вызове которого будет извлекаться индекс текущей сцены при помощью метода Scene.buildIndex. А потом, при помощи метода SceneManager.LoadScene, будет происходить загрузка той сцену, индекс которой мы только что получили.

После написания данного скрипта, сохраняем его, и проделываем следующие шаги.

  • Присваиваем данный скрипт нашему объекту(кнопки Рестарт). Для этого необходимо перетащить наш скрипт в окно Inspector для нашей кнопки.
  • Далее необходимо перетащить сам объект(кнопка Рестарт) в поле On Click (). После чего выбрать название нашего метода, который мы создавали в скрипте, а именно: Scenes — RestartLevel (). (См. рис)

На этом всё! Последний штрих, который остался сделать, это добавить нашу сцену(если не добавлено) в настройках юнити. Для этого в верхнем меню Unity жмём File — Build Settings. . И далее перетаскиваем нашу сцену в настройки сцен, как указано на скриншоте.

Поздравляем, перезагрузка сцены готова на все 100%. Если у Вас возникли какие-либо трудности, пишите в комментариях. А на этом всё. Всем спасибо.

Unity C# — Как сделать перезапуск уровня через 2-3 секунды после смерти персонажа?

Ребята, помогите решить проблему, а то уже голова пухнет. Я только начинаю свой путь в изучении C# и Unity соответственно.

Проблема:
Игрок «исчезает» при соприкосновении с тегом «Enemy» и после этого необходимо сделать рестарт уровня. Я пересмотрел уже сотни статей и видео, ни один предложенный вариант не работает.

На deathplayer привязан Particle system, чтобы при смерти ГГ красиво распадался.

Press ‘R’ to Restart — Loading Scenes in Unity

In the last article, we have created the ‘Game Over’ behavior. This article will cover how to work with scenes and their management. We will do this by allowing the player to restart the scene whenever the ‘Game over’ text is shown.

First setup:

First, we have to go into the ‘Build settings’ of Unity > You can open this up by going into the ‘File’ > ‘Build settings,’ or by pressing the ‘Ctrl + Shift + B’ shortcut by default.

A ‘Build Settings’ window has opened for us. Here click on the ‘Add Open Scenes’ button to add all of your open scenes in the editor. This is important so that Unity knows what scenes you want to work with.

After clicking on the button, a scene should appear in the list. Notice the number which is shown in the right part of the window. This number indicates the ‘buildIndex’ number of each scene.

With the scene prepared, we have to create the actual text that will be shown when the game is over, which will inform the player about the possibility to restart the game. This is done similarly as we did in the previous article — and here is the result that I am going with!

Onto the code!

Now that we have everything set, it is time to code in the behavior. Today, we will make use of the ‘Game Manager,’ which we created some time ago — so let’s go ahead and open up the ‘GameManager’ script.

First up, we need to add a new namespace to the script, allowing us to work with scenes.

Now, all we need to do is check when the game is over, and when the player presses the ‘R’ button, the scene will be reset, and the player can play the game again from the start.

Since we currently have only one scene active in our game, we reference the currently active scene and load it from the start.

Now only one small detail remains, and that is also to show the ‘Restart_game_text’ when the game is over — and we do this by creating a reference for the text in the ‘UIManager’ script and setting it active the same way as we do with the ‘Game_Over_text’.

And that is all! — Now, whenever the player dies, he can simply click the ‘R’ button to reset the level and keep on playing till the end of times.. or more likely, until he falls asleep.

But that is it for now, thank you for reading and feel free to follow me for more articles — and as always, good luck and see you next time!

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

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