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

Как остановить корутину unity

  • автор:

MonoBehaviour.StopCoroutine

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

Declaration

Parameters

methodName Name of coroutine.
routine Name of the function in code, including coroutines.

Description

Stops the first coroutine named methodName , or the coroutine stored in routine running on this behaviour.

StopCoroutine takes one of three arguments which specify which coroutine is stopped:

  • A string function naming the active coroutine
  • The IEnumerator variable used earlier to create the coroutine.
  • The Coroutine to stop the manually created Coroutine .

Note: Do not mix the three arguments. If a string is used as the argument in StartCoroutine, use the string in StopCoroutine. Similarly, use the IEnumerator in both StartCoroutine and StopCoroutine. Finally, use StopCoroutine with the Coroutine used for creation.

MonoBehaviour.StopCoroutine

Останавливает все корутины с именем methodName запущенные на этом MonoBehaviour.

StopCoroutine takes one of three arguments which specify which coroutine is stopped:

— A string function naming the active coroutine
— The IEnumerator variable used earlier to create the coroutine.
— The Coroutine to stop the manually created Coroutine .

Note: Do not mix the three arguments. If a string is used as the argument in StartCoroutine, use the string in StopCoroutine. Similarly, use the IEnumerator in both StartCoroutine and StopCoroutine. Finally, use StopCoroutine with the Coroutine used for creation.

Coroutines

A coroutine allows you to spread tasks across several frames. In Unity, a coroutine is a method that can pause execution and return control to Unity but then continue where it left off on the following frame.

In most situations, when you call a method, it runs to completion and then returns control to the calling method, plus any optional return values. This means that any action that takes place within a method must happen within a single frame update.

In situations where you would like to use a method call to contain a procedural animation or a sequence of events over time, you can use a coroutine.

However, it’s important to remember that coroutines aren’t threads. Synchronous operations that run within a coroutine still execute on the main thread. If you want to reduce the amount of CPU time spent on the main thread, it’s just as important to avoid blocking operations in coroutines as in any other script code. If you want to use multi-threaded code within Unity, consider the C# Job System.

It’s best to use coroutines if you need to deal with long asynchronous operations, such as waiting for HTTP transfers, asset loads, or file I/O to complete.

Coroutine example

As an example, consider the task of gradually reducing an object’s alpha (opacity) value until it becomes invisible:

In this example, the Fade method doesn’t have the effect you might expect. To make the fading visible, you must reduce the alpha of the fade over a sequence of frames to display the intermediate values that Unity renders. However, this example method executes in its entirety within a single frame update. The intermediate values are never displayed, and the object disappears instantly.

To work around this situation, you could add code to the Update function that executes the fade on a frame-by-frame basis. However, it can be more convenient to use a coroutine for this kind of task.

In C#, you declare a coroutine like this:

A coroutine is a method that you declare with an IEnumerator return type and with a yield return statement included somewhere in the body. The yield return null line is the point where execution pauses and resumes in the following frame. To set a coroutine running, you need to use the StartCoroutine function:

The loop counter in the Fade function maintains its correct value over the lifetime of the coroutine, and any variable or parameter is preserved between yield statements.

Coroutine time delay

By default, Unity resumes a coroutine on the frame after a yield statement. If you want to introduce a time delay, use WaitForSeconds:

You can use WaitForSeconds to spread an effect over a period of time, and you can use it as an alternative to including the tasks in the Update method. Unity calls the Update method several times per second, so if you don’t need a task to be repeated quite so often, you can put it in a coroutine to get a regular update but not every single frame.

For example, you can might have an alarm in your application that warns the player if an enemy is nearby with the following code:

If there are a lot of enemies then calling this function every frame might introduce a significant overhead. However, you could use a coroutine to call it every tenth of a second:

This reduces the number of checks that Unity carries out without any noticeable effect on gameplay.

Stopping coroutines

To stop a coroutine, use StopCoroutine and StopAllCoroutines. A coroutine also stops if you’ve set SetActive to false to disable the GameObject 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 the coroutine is attached to. Calling Destroy(example) (where example is a MonoBehaviour instance) immediately triggers OnDisable and Unity processes the coroutine, effectively stopping it. Finally, OnDestroy is invoked at the end of the frame.

Note: If you’ve disabled a MonoBehaviour by setting enabled to false , Unity doesn’t stop coroutines.

Analyzing coroutines

Coroutines execute differently from other script code. Most script code in Unity appears within a performance trace in a single location, beneath a specific callback invocation. However, the CPU code of coroutines always appears in two places in a trace.

All the initial code in a coroutine, from the start of the coroutine method until the first yield statement, appears in the trace whenever Unity starts a coroutine. The initial code most often appears whenever the StartCoroutine method is called. Coroutines that Unity callbacks generate (such as Start callbacks that return an IEnumerator ) first appear within their respective Unity callback.

The rest of a coroutine’s code (from the first time it resumes until it finishes executing) appears within the DelayedCallManager line that’s inside Unity’s main loop.

This happens because of the way that Unity executes coroutines. The C# compiler auto generates an instance of a class that backs coroutines. Unity then uses this object to track the state of the coroutine across multiple invocations of a single method. Because local-scope variables within the coroutine must persist across yield calls, Unity hoists the local-scope variables into the generated class, which remain allocated on the heap during the coroutine. This object also tracks the internal state of the coroutine: it remembers at which point in the code the coroutine must resume after yielding.

Because of this, the memory pressure that happens when a coroutine starts is equal to a fixed overhead allocation plus the size of its local-scope variables.

The code which starts a coroutine constructs and invokes an object, and then Unity’s DelayedCallManager invokes it again whenever the coroutine’s yield condition is satisfied. Because coroutines usually start outside of other coroutines, this splits their execution overhead between the yield call and DelayedCallManager .

You can use the Unity Profiler A window that helps you to optimize your game. It shows how much time is spent in the various areas of your game. For example, it can report the percentage of time spent rendering, animating, or in your game logic. More info
See in Glossary to inspect and understand where Unity executes coroutines in your application. To do this, profile your application with Deep Profiling enabled, which profiles every part of your script code and records all function calls. You can then use the CPU Usage Profiler module to investigate the coroutines in your application.

Profiler session with a coroutine in a DelayedCallProfiler session with a coroutine in a DelayedCall

It’s best practice to condense a series of operations down to the fewest number of individual coroutines possible. Nested coroutines are useful for code clarity and maintenance, but they impose a higher memory overhead because the coroutine tracks objects.

If a coroutine runs every frame and doesn’t yield on long-running operations, it’s more performant to replace it with an Update or LateUpdate callback. This is useful if you have long-running or infinitely looping coroutines.

Корутины

Сопрограмма позволяет распределять задачи по нескольким фреймам. В Unity сопрограмма — это метод, который может приостановить выполнение и вернуть управление Unity, но затем продолжить с того места, на котором остановился, в следующем кадре.

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

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

Однако важно помнить, что сопрограммы — это не потоки. Синхронные операции, выполняемые внутри сопрограммы, по-прежнему выполняются в основном потоке. Если вы хотите уменьшить количество процессорного времени, затрачиваемого на основной поток, так же важно избегать блокирующих операций в сопрограммах, как и в любом другом коде скрипта. Если вы хотите использовать многопоточный код в Unity, обратите внимание на систему заданий C#.

Сопрограммы лучше всего использовать, если вам нужно иметь дело с длительными асинхронными операциями, такими как ожидание передачи HTTP, загрузки ресурсов или завершения файлового ввода-вывода.

Пример сопрограммы

В качестве примера рассмотрим задачу постепенного уменьшения значения альфы (непрозрачности) объекта, пока он не станет невидимым:

В этом примере метод Fade не дает ожидаемого эффекта. Чтобы сделать затухание видимым, вы должны уменьшить альфа-канал затухания в последовательности кадров, чтобы отобразить промежуточные значения, которые отображает Unity. Однако этот пример метода полностью выполняется в рамках одного обновления кадра. Промежуточные значения никогда не отображаются, и объект мгновенно исчезает.

Чтобы обойти эту ситуацию, вы можете добавить код в функцию Update , которая выполняет покадровое затухание. Однако для такого рода задач может быть удобнее использовать сопрограмму.

В C# вы объявляете сопрограмму следующим образом:

Сопрограмма — это метод, который вы объявляете с помощью IEnumerator и с выходом оператор возврата включен где-то в теле. Строка yield return null — это точка, в которой выполнение приостанавливается и возобновляется в следующем кадре. Чтобы запустить сопрограмму, вам нужно использовать функцию StartCoroutine:

Счетчик циклов в функции Fade сохраняет свое правильное значение в течение всего времени существования сопрограммы, и любая переменная или параметр сохраняется между операторами yield .

Время задержки сопрограммы

По умолчанию Unity возобновляет сопрограмму во фрейме после оператора yield . Если вы хотите ввести временную задержку, используйте WaitForSeconds:

Вы можете использовать WaitForSeconds для распространения эффекта на определенный период времени, а также в качестве альтернативы включению задач в Обновить метод. Unity вызывает метод Update несколько раз в секунду, поэтому, если вам не нужно, чтобы задача повторялась так часто, вы можете поместить ее в сопрограмму, чтобы получать регулярное обновление. но не каждый кадр.

Например, в вашем приложении может быть будильник, который предупреждает игрока о приближении врага с помощью следующего кода:

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

Это уменьшает количество проверок, которые выполняет Unity, без заметного влияния на игровой процесс.

Остановка сопрограмм

Чтобы остановить сопрограмму, используйте StopCoroutine и Остановить все сопрограммы. Сопрограмма также останавливается, если вы установили для SetActive значение false , чтобы отключить GameObject Фундаментальный объект в сценах Unity, который может представлять персонажей, реквизит, декорации, камеры, путевые точки и многое другое. Функциональность GameObject определяется прикрепленными к нему компонентами. Подробнее
См. в Словарь , к которому прикреплена сопрограмма. Немедленный вызов Destroy(example) (где example – это экземпляр MonoBehaviour ) запускает OnDisable, и Unity обрабатывает сопрограмму, фактически останавливая ее. Наконец, в конце кадра вызывается OnDestroy .

Примечание. Если вы отключили MonoBehaviour , установив enabled значение false , Unity не останавливает сопрограммы.

Анализ сопрограмм

Корутины выполняются иначе, чем код других скриптов. Большая часть кода сценария в Unity отображается в трассировке производительности в одном месте, под определенным вызовом обратного вызова. Однако код ЦП сопрограмм всегда появляется в двух местах трассировки.

Весь исходный код сопрограммы, от начала метода сопрограммы до первого оператора yield , появляется в трассировке каждый раз, когда Unity запускает сопрограмму. Исходный код чаще всего появляется всякий раз, когда вызывается метод StartCoroutine. Сопрограммы, генерируемые обратными вызовами Unity (например, обратные вызовы Start , которые возвращают IEnumerator ), сначала появляются в соответствующем обратном вызове Unity.

Остальная часть кода сопрограммы (с момента ее первого возобновления до завершения выполнения) отображается в строке DelayedCallManager , которая находится внутри основного цикла Unity.

Это происходит из-за того, как Unity выполняет сопрограммы. компилятор C# автоматически создает экземпляр класса, который поддерживает сопрограммы. Затем Unity использует этот объект для отслеживания состояния сопрограммы при нескольких вызовах одного метода. Поскольку переменные локальной области внутри сопрограммы должны сохраняться при вызовах yield , Unity поднимает переменные локальной области видимости в сгенерированный класс, который остается выделенным в куче во время сопрограммы. Этот объект также отслеживает внутреннее состояние сопрограммы: он запоминает, в какой точке кода сопрограмма должна возобновить работу после завершения.

Из-за этого нехватка памяти, возникающая при запуске сопрограммы, равна сумме фиксированных накладных расходов и размера ее переменных локальной области.

Код, который запускает сопрограмму, создает и вызывает объект, а затем Unity DelayedCallManager снова вызывает его всякий раз, когда сопрограмма yield состояние устраивает. Поскольку сопрограммы обычно запускаются вне других сопрограмм, это распределяет их выполнение между вызовом yield и вызовом DelayedCallManager .

Вы можете использовать окно Unity Profiler , которое поможет вам оптимизировать игру. Он показывает, сколько времени вы тратите на различные области вашей игры. Например, он может сообщать о проценте времени, затраченном на рендеринг, анимацию или игровую логику. Дополнительная информация
См. Словарь , чтобы изучить и понять, где Unity выполняет сопрограммы в вашем приложении. Для этого профилируйте свое приложение с включенным глубоким профилированием, которое профилирует каждую часть кода вашего скрипта и записывает все вызовы функций. Затем вы можете использовать модуль CPU Usage Profiler для исследования сопрограмм в вашем приложении.

Сеанс профилировщика с сопрограммой в DelayedCallСеанс профилировщика с сопрограммой в DelayedCall

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

Если сопрограмма запускается в каждом кадре и не дает выгоды при длительных операциях, более эффективно заменить ее Update или обратный вызов LateUpdate . Это полезно, если у вас есть длинные или бесконечно зацикленные сопрограммы.

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

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