I have a simple script for a third person camera to rotate 90° once a button is pressed. I use a coroutine to rotate the camera here, but for some reason, the second time the coroutine runs, it won’t stop even though transform.rotation.eulerangles.yis equal torotateTowards
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraBehaviour : MonoBehaviour
{
public float rotationSpeed;
public KeyCode rotateRight, rotateLeft;
private bool isRotating = false;
private float rotatingTowards;
private Coroutine rotationRoutine = null;
// Update is called once per frame
void Update()
{
rotate();
}
void rotate()
{
if (!isRotating)
{
if (Input.GetKeyDown(rotateRight))
{
rotatingTowards = transform.rotation.eulerAngles.y - 90;
rotationRoutine = StartCoroutine(rotate(rotatingTowards));
isRotating = true;
}
if (Input.GetKeyDown(rotateLeft))
{
rotatingTowards = transform.rotation.eulerAngles.y + 90;
rotationRoutine = StartCoroutine(rotate(rotatingTowards));
isRotating = true;
}
} else
{
Debug.Log("rot = " + transform.rotation.eulerAngles.y + " goal = " + rotatingTowards);
if (transform.rotation.eulerAngles.y == rotatingTowards)
{
Debug.Log("stopping coroutine");
StopCoroutine(rotationRoutine);
isRotating = false;
}
}
}
private IEnumerator rotate(float towards)
{
while (transform.rotation.eulerAngles.y != towards)
{
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(new Vector3(0, towards, 0)), rotationSpeed);
yield return new WaitForFixedUpdate();
}
}
}