johnny 5
johnny 5

Reputation: 21005

Unity Easing over time should fire once

I'm trying to create a function that rotates over a period of time, I call it from a co-routine triggered by a button. The Coroutine executes fine, the only issue is that you can fire it multiple times.

protected bool _isRotating = false;
public IEnumerator RotateWithEasing(GameHelper.Axis axis, float inTime)
{
    _isRotating = true;
    if(_isRotating)
    {
        yield return null;
    }

    var degrees = this.GetDegreesFromAxis(axis);

    Quaternion fromAngle = transform.rotation;
    Quaternion toAngle = Quaternion.Euler(transform.eulerAngles + degrees);
    for (float t = 0f; t < 1f; t += Time.deltaTime / inTime)
    {
        transform.rotation = Quaternion.Lerp(fromAngle, toAngle, t);
        yield return null;
    }

    _isRotating = false;
}

How can I have this fire once and not register to fire again until after the rotation is complete?

Upvotes: 1

Views: 69

Answers (1)

Programmer
Programmer

Reputation: 125435

Use yield break. It is like the return keyword in a void function. It will return/exist from the function. Also put the _isRotating = true; after the if statement instead of before it. Leave the rest of the code where they are.

Change

 _isRotating = true;
 if(_isRotating)
 {
   yield return null;
 }

to

if (_isRotating)
{
    yield break;
}
_isRotating = true;

Upvotes: 2

Related Questions