- Home /
 
figured it out!
Coroutine not stopping with rotation (stuck on infinite loop).
I have a coroutine to rotate a gameobject over 1 second by 360 on the y axis when the player enters the trigger. My problem is that it doesn't just rotate once but keeps on rotating.
 public class Educational_Card_PopUp : MonoBehaviour
 {
     public Image card1;
     public GameObject E_card1;
  
 
     void PopUP()
     {
         E_card1.SetActive(true);
         StartCoroutine(RotateOnStart(1));
 
     }
 
     IEnumerator RotateOnStart(float duration)
     {
   
         Vector3 startRotation = transform.eulerAngles;
         float endRotation = startRotation.y + 360.0f;
         float t = 0.0f;
 
 
         while (t < duration)
         {
             Debug.Log(t);
             t += Time.deltaTime;
             float yRotation = Mathf.Lerp(startRotation.y, endRotation, t / duration) % 360.0f;
             transform.eulerAngles = new Vector3(startRotation.x, yRotation, startRotation.z);
             
             yield return null;
         }
        
     }
 
     private void OnTriggerEnter(Collider other)
     {
         if (other.CompareTag("Player"))
         {
             card1.rectTransform.sizeDelta = new Vector2(2, 2);
             PopUP();
         }
     }
 }
 
               Using debug.log i found out my issue is the coroutine doesn't end when t > duration but instead t keeps bouncing back to 0. So the rotation never ends. Everytime t reaches more than 0 it loops back to 0 and i get an infinite rotation.
Any idea what i'm doing wrong and could someone explain it please?
Answer by The_Mean_Fiddler · Apr 21, 2021 at 04:07 AM
I guess OnTriggerEnter keeps getting called
Your right! For testing purposes i just connected the coroutine to a getkeydown in update and it works exactly how i want it to.
Is there a reason OnTriggerEnter keeps getting called? I thought it only gets called once when the player is say in the trigger. Or is that not the case.
is it cos its rotating? the collider is spinning?