Dtb49
Dtb49

Reputation: 1271

How to prevent an interruption to a Coroutine that causes it to restart/repeat itself in Unity?

In my project I have an object and some buttons. When I press one of the buttons, the object Slerps to a new rotation in a coroutine. The bug occurs when the user presses the button before the coroutine has a chance to finish the method the first time. In which case, it basically restarts the slerp movement from the starting rotation to the new rotation. Is there a way to prevent this from happening? I can do it using a Boolean and checking whether the coroutine is still in the middle of slerping but, an ideal solution would be one where it stops the slerp where it is and then slerps to the new rotation. Below is the coroutine I use on my button:

public IEnumerator SlerpRotation(Transform trans, Quaternion slerpTo)
{
        timer = 0;
        Quaternion rotation = trans.localRotation;
        while (timer < 2)
        {
            trans.localRotation = Quaternion.Slerp(rotation, slerpTo, timer/2f);
            timer += Time.deltaTime;
            yield return null;
        }
}

Before I get to this method I have another method that basically just checks if it is equal to two other angles and toggling between the two angles.

Upvotes: 0

Views: 272

Answers (1)

ZayedUpal
ZayedUpal

Reputation: 1601

You can save the Coroutine to a variable. Whenever you need to start the Coroutine, you can stop the Coroutine first and then start again. Like this:

float timer;
Coroutine theCoroutine;

public void SlerpRot(){
    if (theCoroutine != null)
        StopCoroutine (theCoroutine);
    theCoroutine = StartCoroutine (SlerpRotation(this.transform,Quaternion.identity));
}
public IEnumerator SlerpRotation(Transform trans, Quaternion slerpTo)
{
    timer = 0;
    Quaternion rotation = trans.localRotation;
    while (timer < 2)
    {
        trans.localRotation = Quaternion.Slerp(rotation, slerpTo, timer/2f);
        timer += Time.deltaTime;
        yield return null;
    }
}

Upvotes: 2

Related Questions