The question is answered, right answer was accepted
Coroutine does not stop?
I have called a coroutine to print out text given to it from another class. I want to disable the textfield after a set amount of seconds, and hence I used a coroutine. I do not want to use setActive() because my script is attached to the text field itself.
I'm calling the coroutine through a function that is called by another class, which checks a bool as to whether my coroutine is running or not. If it is, I want it stopped and started with the new parameter. However, when I run the script, the coroutine does not appear to be stopped (i.e. the text background still disappears after a few seconds on every coroutine call).
Is there any problem with the script? Thanks.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIPrinter : MonoBehaviour {
public Text textField;
public float textTime = 2;
private bool printingText = false;
private void Start()
{
textField = GetComponent<Text>();
}
public void UIPrint(string textToPrint)
{
if (printingText)
{
StopCoroutine("PrintText");
}
StartCoroutine(PrintText(textToPrint));
}
public IEnumerator PrintText(string textToPrint)
{
printingText = true;
textField.text = textToPrint;
transform.parent.gameObject.GetComponent<Image>().color = new Color32(0, 0, 0, 150);
yield return new WaitForSecondsRealtime(textTime);
transform.parent.gameObject.GetComponent<Image>().color = new Color32(0, 0, 0, 0);
textField.text = "";
printingText = false;
}
Answer by Hellium · Apr 23, 2018 at 09:18 AM
The documentation says:
Note: Do not mix the three arguments. If a string is used as the argument in StartCoroutine, use the string in StopCoroutine. Similarly, use the IEnumerator in both StartCoroutine and StopCoroutine. Finally, use StopCoroutine with the Coroutine used for creation
public class UIPrinter : MonoBehaviour {
public Text textField;
public float textTime = 2;
private IEnumerator coroutine;
private void Start()
{
textField = GetComponent<Text>();
}
public void UIPrint(string textToPrint)
{
if (coroutine != null)
{
StopCoroutine(coroutine);
}
coroutine = PrintText(textToPrint);
StartCoroutine( coroutine );
}
public IEnumerator PrintText(string textToPrint)
{
textField.text = textToPrint;
transform.parent.gameObject.GetComponent<Image>().color = new Color32(0, 0, 0, 150);
yield return new WaitForSecondsRealtime(textTime);
transform.parent.gameObject.GetComponent<Image>().color = new Color32(0, 0, 0, 0);
textField.text = "";
coroutine = null;
}
}
How do I assign the PrintText IEnumerator to the "coroutine" variable?
As indicated in my code:
coroutine = PrintText(textToPrint)
Ah woops. Didn't catch that. Thanks for your help!
Follow this Question
Related Questions
Coroutine not stopping 0 Answers
After stop coroutine it resumes its task when I call start coroutine 1 Answer
Can I check if this.gameObject was destroyed? 5 Answers
Need help using coroutines 1 Answer