Coroutines: Dynamic Text
Coroutines
A coroutine is like a function that has the ability to pause execution and return control to Unity but then to continue where it left off on the following frame. It is essentially a function declared with a return type of IEnumerator and with the yield return statement included somewhere in the body. The
yield return null;
code is the point at which execution will pause and be resumed the following frame.
To set a coroutine running, you need to use the StartCoroutine function: In the DialogManager StartCoroutine is executed each time the GetNextDialog( ) Method is Executed:
You can call the Unity StopAllCoroutines( ) method to stop any prior execution
//this allows single characters to be added to look like typed text
IEnumerator TypeSentence(string sentence)
{
dialogText.text = ""; //clear previous sentance
foreach (char letter in sentence.ToCharArray())
{
dialogText.text += letter;
yield return new WaitForSeconds(0.05f); //execution pauses here
}
}/
//Example Use: in GetNextDialog( ) method
StopAllCoroutines(); //stop if still running from prior dialog
string curSentence = item.dialogText;
StartCoroutine( TypeSentence( curSentence ) );
Last updated
Was this helpful?