# Coroutines: Dynamic Text

## Coroutines

[See Unity Manual](https://docs.unity3d.com/Manual/Coroutines.html)

> 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**.&#x20;

To set a coroutine running, you need to use the[ StartCoroutine](https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html) 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

```csharp
//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 ) );
```
