Coroutine with Slerp causing crash

Hey, I have a coroutine that is used to rotate the player towards the direction of an object over a span of one second. This coroutine seems to cause Unity to crash whenever the amount needed to rotate is very little (such as when player is almost already facing towards the intended direction).
I was hoping some light could be shed as to why this happens, and how I can fix this issue.

 private IEnumerator RotateToObject()
    {
       
        Quaternion newRotation = Quaternion.LookRotation((jumpscarePosition - Player.transform.position), Vector3.up);
        newRotation.x = 0f;
        newRotation.z = 0f;
        for (float i = 0f; i < 1f; i += Time.deltaTime)
        {
            float factor = i / 1f;
            Player.transform.rotation = Quaternion.Slerp(Player.transform.rotation, newRotation, factor);
            yield return null;
        }

        Player.transform.rotation = newRotation;
        yield break;
    }

Personally I’m not fond of coroutines for this stuff. I would just do it all the time.

using UnityEngine;

// @kurtdekker - put this script on an object, it will
// constantly slerp to another object's rotation.

public class Slerpalicious : MonoBehaviour
{
    [Header("Transform to copy rotation from.")]
    public Transform Source;

    [Header("How fast to slerp? (fractional alpha)")]
    public float Snappiness = 5.0f;

    void Update()
    {
        transform.rotation = Quaternion.Slerp(transform.rotation, Source.rotation, Snappiness * Time.deltaTime);
    }
}

If you need the object to NOT rotate, then just disable the above script, switch it back on when you want it to start rotating.

If you care for one second exactly, you can just keep your own separate timer.

The above is just a specific instance of this mechanism:

Smoothing movement between any two particular values:

You have currentQuantity and desiredQuantity.

  • only set desiredQuantity
  • the code always moves currentQuantity towards desiredQuantity
  • read currentQuantity for the smoothed value

Works for floats, Vectors, Colors, Quaternions, anything continuous or lerp-able.

The code: SmoothMovement.cs · GitHub