- Home /
 
Stop and start fresh coroutine
Hi! I have this coroutine that show text for 3.5 seconds and then fades it away when an object is clicked. The problem is when I click multiple time the fading becomes all jerky the coroutine starts multiple times.
I know that I have to stop the coroutine and start it again but I cannot seem to make it work. here is the code I have
 using UnityEngine;
 using UnityEngine.UI;
 using System.Collections;
 
 public class fadeDialogText : MonoBehaviour
 {
     float readTime = 3.5f; //Seconds to read the text
 
     IEnumerator FadeTextToZeroAlpha(float time, Text i)
     {
         yield return new WaitForSeconds (readTime);
         i.color = new Color(i.color.r, i.color.g, i.color.b, 1);
         while (i.color.a > 0.0f)
         {
             i.color = new Color(i.color.r, i.color.g, i.color.b, i.color.a - (Time.deltaTime / time));
             yield return null;
         }
     }
     public void startFadingDialogText()
     {
         StopAllCoroutines (); // trying to stop the coroutine but doesnt work
         StartCoroutine(FadeTextToZeroAlpha(1f, GetComponent<Text>())); // start new fade
     }
 }
 
               Thanks for your help!!
I tested your code, no problem for me. How do you call startFadingDialogText method? 
I call it like this ..
 dialogTextOtherObject.GetComponent<fadeDialogText>().startFadingDialogText(); 
 
                   but still when I click the object, the text appear and fade away correctly the first time .. but second time, or when clicked multiple times, it flickers and mess up.
It does not start the current coroutine and start a new one...
Can you see why?
thanks for you help!!
Oh I got it!!! just switched this...
      IEnumerator FadeTextToZeroAlpha(float time, Text i)
      {
          yield return new WaitForSeconds (readTime);
          i.color = new Color(i.color.r, i.color.g, i.color.b, 1);
          while (i.color.a > 0.0f)
          {
 
                  to this...
     IEnumerator FadeTextToZeroAlpha(float time, Text i)
     {
         i.color = new Color(i.color.r, i.color.g, i.color.b, 1);
         yield return new WaitForSeconds (readTime);
         while (i.color.a > 0.0f)
         {
 
                  Thanks!!!
Your answer
 
             Follow this Question
Related Questions
Fading out GUI Label using coroutine problem 2 Answers
Font renders incorrectly 1 Answer
Why is my coroutine skipping a method? 1 Answer
Write text letter by letter with return if word does not suit in line 1 Answer
Strange Interaction Between UI, Coroutines, and Content Fitters: Corrections Are Very Welcome 0 Answers