How does unity solve the program stuck caused by the frequent opening of the coroutine?

How does unity solve the program stuck caused by the frequent opening of the coroutine?

1. Coroutine

The coroutine does not create a new thread for execution in Unity, and its execution still occurs in the main thread. When we have a time-consuming operation, we can distribute the operation to a few frames or a few seconds to complete, instead of waiting for the operation to complete in one frame before performing other operations.

2. The coroutine is opened frequently

The coroutine in unity needs to judge whether it is turned on before starting, otherwise the coroutine will continue to superimpose

3. Solution

Solution 1:
Before starting the coroutine, it is necessary to determine whether the coroutine is enabled, and stop and re-open the opened one:
that is, before starting the coroutine, close the previously opened one.
private Coroutine coroutine_setReConnect;
if (coroutine_setReConnect != null)
{ StopCoroutine(coroutine_setReConnect); coroutine_setReConnect = null; } coroutine_setReConnect = StartCoroutine(IE_SetReConnect());



Solution 2:
Define a bool value yourself to judge whether the coroutine is executing. If the coroutine cannot be started during execution,
judge that the bool is false at the beginning to start the coroutine
if(!bIsStartCoroutine)
A();
private void A()
{

      bIsStartCoroutine = true;
        StartCoroutine(B() as IEnumerator);

}
private IEnumerator B()
{

  yield return null;
    bIsStartCoroutine = false;
}

Guess you like

Origin blog.csdn.net/lucky_XiaoZhang/article/details/127852456