Unity/Csharp/Coroutine
提供: 初心者エンジニアの簡易メモ
コルーチンとは
- 条件になるまで待機するもの
- 類似なものとして、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秒ごとに実行できる。
