Version: 2022.3
言語: 日本語
イベント関数
名前空間

コルーチン

A coroutine allows you to spread tasks across several frames. In Unity, a coroutine is a method that can pause execution and return control to Unity but then continue where it left off on the following frame.

In most situations, when you call a method, it runs to completion and then returns control to the calling method, plus any optional return values. This means that any action that takes place within a method must happen within a single frame update.

In situations where you would like to use a method call to contain a procedural animation or a sequence of events over time, you can use a coroutine.

ただし、コルーチンはスレッドではないことに注意してください。コルーチン内で実行される同期操作は、メインスレッドで実行されることに変わりありません。メインスレッドに費やされる CPU 時間を削減したい場合は、他の多くのスクリプトコードと同様に、コルーチン内でのブロック操作を避けることが重要です。Unity 内でマルチスレッドコードを使用したい場合は、C# ジョブシステム を検討してください。

HTTP 転送の待機、アセットのロードの待機、ファイル出入力の完了待ちなど、長い非同期処理を行う必要がある場合は、コルーチンの使用が最適です。

Coroutine example

As an example, consider the task of gradually reducing an object’s alpha (opacity) value until it becomes invisible:

void Fade()
{
    Color c = renderer.material.color;
    for (float alpha = 1f; alpha >= 0; alpha -= 0.1f)
    {
        c.a = alpha;
        renderer.material.color = c;
    }
}

In this example, the Fade method doesn’t have the effect you might expect. To make the fading visible, you must reduce the alpha of the fade over a sequence of frames to display the intermediate values that Unity renders. However, this example method executes in its entirety within a single frame update. The intermediate values are never displayed, and the object disappears instantly.

この状況は、フレーム単位でフェードを実行する Update 関数にコードを追加することで回避できます。ただし、この種のタスクには、コルーチンを使用する方が便利な場合があります。

In C#, you declare a coroutine like this:

IEnumerator Fade()
{
    Color c = renderer.material.color;
    for (float alpha = 1f; alpha >= 0; alpha -= 0.1f)
    {
        c.a = alpha;
        renderer.material.color = c;
        yield return null;
    }
}

コルーチンは、IEnumerator 戻り値型で宣言し、yield return ステートメントをボディのどこかに含むメソッドです。yield return null の行は、実行が一時停止し、次のフレームで再開されるポイントです。コルーチンの実行を設定するには、以下のように StartCoroutine 関数を使用する必要があります。

void Update()
{
    if (Input.GetKeyDown("f"))
    {
        StartCoroutine(Fade());
    }
}

The loop counter in the Fade function maintains its correct value over the lifetime of the coroutine, and any variable or parameter is preserved between yield statements.

Coroutine time delay

By default, Unity resumes a coroutine on the frame after a yield statement. If you want to introduce a time delay, use WaitForSeconds:

IEnumerator Fade()
{
    Color c = renderer.material.color;
    for (float alpha = 1f; alpha >= 0; alpha -= 0.1f)
    {
        c.a = alpha;
        renderer.material.color = c;
        yield return new WaitForSeconds(.1f);
    }
}

You can use WaitForSeconds to spread an effect over a period of time, and you can use it as an alternative to including the tasks in the Update method. Unity calls the Update method several times per second, so if you don’t need a task to be repeated quite so often, you can put it in a coroutine to get a regular update but not every single frame.

For example, you can might have an alarm in your application that warns the player if an enemy is nearby with the following code:

bool ProximityCheck()
{
    for (int i = 0; i < enemies.Length; i++)
    {
        if (Vector3.Distance(transform.position, enemies[i].transform.position) < dangerDistance) {
                return true;
        }
    }

    return false;
}

敵が数多く存在する場合は、この関数を毎フレーム呼び出しすると著しいオーバーヘッドが生じるかもしれません。しかし、コルーチンを使用して 1/10 秒ごとに呼び出すことができます。

IEnumerator DoCheck()
{
    for(;;)
    {
        if (ProximityCheck())
        {
            // Perform some action here
        }
        yield return new WaitForSeconds(.1f);
    }
}

This reduces the number of checks that Unity carries out without any noticeable effect on gameplay.

Stopping coroutines

To stop a coroutine, use StopCoroutine and StopAllCoroutines. A coroutine also stops if you’ve set SetActive to false to disable the GameObject the coroutine is attached to. Calling Destroy(example) (where example is a MonoBehaviour instance) immediately triggers OnDisable and Unity processes the coroutine, effectively stopping it. Finally, OnDestroy is invoked at the end of the frame.

Note: If you’ve disabled a MonoBehaviour by setting enabled to false, Unity doesn’t stop coroutines.

Analyzing coroutines

コルーチンは、他のスクリプトコードからは、異なる形で実行されます。Unity では、ほとんどのスクリプトコードは、パフォーマンストレース内で、特定のコールバック呼び出しの下の 1 箇所で出現します。ただし、コルーチンの CPU コードは、トレース内で常に 2 箇所に出現します。

All the initial code in a coroutine, from the start of the coroutine method until the first yield statement, appears in the trace whenever Unity starts a coroutine. The initial code most often appears whenever the StartCoroutine method is called. Coroutines that Unity callbacks generate (such as Start callbacks that return an IEnumerator) first appear within their respective Unity callback.

The rest of a coroutine’s code (from the first time it resumes until it finishes executing) appears within the DelayedCallManager line that’s inside Unity’s main loop.

これが起こる理由は、Unity がコルーチンを実行する方法にあります。C#コンパイラー は、コルーチンに対応するクラスのインスタンスを自動生成します。その上で Unity がこのオブジェクトを使用して、1 つのメソッドの複数の呼び出しにわたってコルーチンの状態を追跡します。コルーチン内のローカルスコープ変数は複数の yield呼び出しにわたって持続する必要があるため、Unity は、生成されたクラス内にローカルスコープ変数を巻き上げ、これはコルーチンの間中ヒープ上に割り当てられたままになります。また、このオブジェクトはコルーチンの内部状態の追跡も行います。つまり、yield 後にコードのどの時点でコルーチンが再開しなければならないかを記憶しています。

Because of this, the memory pressure that happens when a coroutine starts is equal to a fixed overhead allocation plus the size of its local-scope variables.

The code which starts a coroutine constructs and invokes an object, and then Unity’s DelayedCallManager invokes it again whenever the coroutine’s yield condition is satisfied. Because coroutines usually start outside of other coroutines, this splits their execution overhead between the yield call and DelayedCallManager.

You can use the Unity Profiler to inspect and understand where Unity executes coroutines in your application. To do this, profile your application with Deep Profiling enabled, which profiles every part of your script code and records all function calls. You can then use the CPU Usage Profiler module to investigate the coroutines in your application.

Profiler session with a coroutine in a DelayedCall
Profiler session with a coroutine in a DelayedCall

It’s best practice to condense a series of operations down to the fewest number of individual coroutines possible. Nested coroutines are useful for code clarity and maintenance, but they impose a higher memory overhead because the coroutine tracks objects.

If a coroutine runs every frame and doesn’t yield on long-running operations, it’s more performant to replace it with an Update or LateUpdate callback. This is useful if you have long-running or infinitely looping coroutines.

イベント関数
名前空間
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961