facebook twitter hatena line email

「Unity/Csharp/Coroutine」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(コールチンのキャンセル)
 
(同じ利用者による、間の1版が非表示)
行1: 行1:
==コールチンとは==
+
==コルーチンとは==
 
*条件になるまで待機するもの
 
*条件になるまで待機するもの
 
*類似なものとして、UniTaskがある
 
*類似なものとして、UniTaskがある
行32: 行32:
 
</pre>
 
</pre>
 
参考:https://tofgame.hatenablog.com/entry/2019/04/10/141614
 
参考:https://tofgame.hatenablog.com/entry/2019/04/10/141614
==コールチンのキャンセル==
+
==コルーチンのキャンセル==
 
<pre>
 
<pre>
 
using System.Collections;
 
using System.Collections;

2025年8月19日 (火) 13:10時点における最新版

コルーチンとは

  • 条件になるまで待機するもの
  • 類似なものとして、UniTaskがある

unity/UniTask [ショートカット]

数秒後まで待機

using System.Collections;
private void Start() {
  StartCoroutine(DelayMethod1(5.0f, 123));
}
IEnumerator DelayMethod1(float delay, int hoge) {
  yield return new WaitForSeconds(delay);
  // ここに処理を追加
}

unity/Csharp/Invoke [ショートカット]

入力待機

エンターキーを入力するまで待つ

using System.Collections;
private void Start() {
  StartCoroutine(WaitInput());
}
IEnumerator WaitInput () {
    yield return new WaitUntil(() => Input.GetKeyDown(KeyCode. Return));
    // yield return new WaitWhile(() => !Input.GetKeyDown(KeyCode.Return)); // WaitWhileの場合は、条件に当てはまらないときに、先にすすめる
    // ここに処理を追加
}

参考:https://tofgame.hatenablog.com/entry/2019/04/10/141614

コルーチンのキャンセル

using System.Collections;
Coroutine coroutine;
private void Start()
{
  coroutine = StartCoroutine(WaitInput());
}
private void Update()
{
  if (Input.GetKeyDown(KeyCode.Space))
  {
     StopCoroutine(coroutine);
  }
}

連続実行

public class CoroutineWaitContinueScene : MonoBehaviour
{
    IEnumerator Start()
    {
        Debug.Log("start");
        yield return StartCoroutine(WaitInput());
        Debug.Log("middle");
        yield return StartCoroutine(WaitInput());
        Debug.Log("end");
    }
    IEnumerator WaitInput()
    {
        yield return new WaitForSeconds(1f);//1秒待つ
        Debug.Log("1s!!");
        yield return new WaitForSeconds(1f);//1秒待つ
        Debug.Log("1s!!");
        yield return new WaitForSeconds(1f);//1秒待つ
        Debug.Log("1s!!");
    }
}

1秒ごとに実行できる。

WaitUntilは1フレーム消費する

参考:https://qiita.com/kema/items/0c80483d828d101b0693