遅延して処理をする

遅延してメソッドを発火させる方法はいくつもあります。 状況に応じて使い分けましょう。

Invokeを使う方法

void Start()
{
  Invoke("DelayMethod", 1.0f);
}
void DelayMethod()
{
  Debug.Log("Invoke");
}

StartCoroutineを使う方法

void Start()
{
  Coroutine coroutine = StartCoroutine("DelayMethod", 1.0f);
}

private IEnumerator DelayMethod(float waitTime)
{
  yield return new WaitForSeconds(waitTime);
  Debug.Log("StartCoroutine");
}

StopCoroutine (coroutine);で止めることができる。

StartCoroutineを使う方法(関数をアロー関数で指定したい場合)

void Start()
{
  Coroutine coroutine = StartCoroutine(DelayMethod(1.0f, () => {
    Debug.Log("StartCoroutine");
  }));
}

private IEnumerator DelayMethod(float waitTime, Action action)
{
  yield return new WaitForSeconds(waitTime);
  action();
}

StartCoroutineを使う方法(関数をアロー関数で指定し、引数も渡したい場合)

void Start()
{
  Coroutine coroutine = StartCoroutine(DelayMethod(1.0f, (int id) => {
    Debug.Log("StartCoroutine: "+id);
  }, 0));
}

private IEnumerator DelayMethod<T>(float waitTime, Action<T> action, T t)
{
  yield return new WaitForSeconds(waitTime);
  action(t);
}

Taskを使う方法

まず Tasks を読み込みます。

using System.Threading.Tasks;

メソッドで実行:

private async void DelayMethod()
{
  await Task.Delay(1000);
  Debug.Log("DelayMethod");
}

メソッドで実行(戻り値に Task を受け取りたい場合):

private async Task DelayMethod()
{
    await Task.Delay(1000);
    Debug.Log("DelayMethod");
}

private async Start()
{
  Task task = DelayMethod();
  await task;
}

引数を渡したり返したり:

private async Task<int> DelayMethod(int id)
{
  await Task.Delay(1000);
  Debug.Log("DelayMethod: " + id);
  return id;
}

private async void Start()
{
  int id = await DelayMethod(1);
  Debug.Log("DelayMethod(return): " + id);
}

アロー関数で実行:

Task.Run(async () => {
  await Task.Delay(1000);
  print("Task.Run");
});

ラッパークラスを作る方法

DelayUtil.cs

Coroutine coroutine = DelayUtil.Delay (1.0f, (int id) => {
  Debug.Log ("DelayUtil.Delay: "+id);
}, 10);

キャンセルはDelayUtil.Stop(coroutine);

MonoBehaviourを拡張する方法

MonoBehaviorExtentsion

Coroutine coroutine = this.Delay(1.0f, (int id) => {
  print("Delay: "+id);
}, 0);

DOTweenを使う方法

DOVirtual.DelayedCall (1.0f, () => {
  print ("DOVirtual.DelayedCall");
});

UniRxを使う方法

Timerを使用する方法

Observable.Timer(TimeSpan.FromSeconds(1.0f))
  .Subscribe(_ => {
    print("UniRx Observable.Timer");
  });

TimerFrameを使用する方法

Observable.TimerFrame(1)
  .Subscribe(_ => {
    print("UniRx Observable.TimerFrame");
  });

Delayを使用する方法(引数が無い時)

Observable.Return(Unit.Default)
  .Delay(TimeSpan.FromSeconds(1.0f))
  .Subscribe(_ => {
    print("UniRx Observable.Delay");
  });

Delayを使用する方法(引数を渡したい時)

Observable.Return(0)
  .Delay(TimeSpan.FromSeconds(1.0f))
  .Subscribe((int id) => {
    print("UniRx Observable.Delay: "+id);
  });