概要
例えば、あるボタンが押されるまで待機する処理をコルーチンで記述する際に、
yield return WaitForUntil(()=>(条件式));
といちいち記述するのは面倒です。
ですが、CustomYieldInstructionを継承したクラスを作成して呼び出せば、簡潔に呼び出せるようです。。
「CustomYieldInstruction」に関しては参考サイトの公式ドキュメントに詳しく記載されています。
nフレーム待機するコルーチン
コード
using UnityEngine; public class WaitForFrames : CustomYieldInstruction { int i = 0; int count; public override bool keepWaiting { get { if (i < count) { i++; return true; } else { return false; } } } public WaitForFrames(int a) { count = a; } }
使用例(5フレームだけ待機)
yield return new WaitForFrames(5);
指定したキーボードが押されるまで待機する
コード
using System.Collections; using System.Collections.Generic; using UnityEngine; public class WaitForKeyDown : CustomYieldInstruction { KeyCode keyCode; public override bool keepWaiting { get { return !Input.GetKeyDown(keyCode); } } public WaitForKeyDown(KeyCode k) { keyCode = k; } }
使用例(Kが押されるまで待機)
yield return new WaitForKeyDown(KeyCode.K);
画面タッチ or マウスの左クリックまで待機
using UnityEngine; public class WaitForScreenTouch : CustomYieldInstruction { public override bool keepWaiting { get { return !Input.GetMouseButtonDown(0); } } }