Log in
04
February

Unity’s Coroutines in C#

Written by DynamicHead. No comments Posted in: Professional
Tagged with , , , , ,

Here is an example how to use Unity’s Coroutines in C#:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using System.Collections;
using UnityEngine;
/*
**Make sure the name of this script file is SomeClass.cs
**like the name of the MonoBehavior class
*/
 
public class SomeClass : MonoBehaviour
{
    //Assuming the SomeClass script is attached
    //to a 3D object which is located at position 0, 0, 0.
    private Vector3 m_Movement = new Vector3(0f, 1f, 0f);
 
    //Used for initialization
    private void Start()
    {
        //Run the method SomeCoroutine and "quit" method Start
        //before the coroutine has been processed to the end.
        StartCoroutine( SomeCoroutine () );
    }
 
    //a C# coroutine
    private IEnumerator SomeCoroutine () 
    {
        // Wait for one frame, then continue.
        yield return 0;
 
        // Wait for two seconds, then continue.
        yield return new WaitForSeconds (2f);
 
        //Launch a coroutine method and wait until it was
        //completely executed, then continue.
        yield return StartCoroutine( AnimateSomeGameObject() );
 
        //Launch a coroutine method and don't wait
        //until it is executed to the end.
        StartCoroutine( ResetSomeObject() );
    }
 
    private IEnumerator AnimateSomeGameObject()
    {
        //Move the 3D object one unit per frame until its position Y
        //is 100, then return to method SomeCoroutine
        while( this.transform.position.y < 100 )
        {
            this.transform.position += m_Movement;
            yield return 0;
        }
    }
 
    private IEnumerator ResetSomeObject()
    {
        //If position Y of the 3D object is already 0
        //quit this method directly
        if (this.transform.position.y == 0f)
            yield break;
 
        //Move the 3D object one unit per frame until
        //its position Y is 0.	
        while (this.transform.position.y > 0)
        {
            this.transform.position -= m_Movement;
            yield return 0;
        }
    }
}