LoginSignup
40
25

More than 5 years have passed since last update.

UniRxのシンプルなサンプル その9(TimerとInterval 一定時間後に実行)

Last updated at Posted at 2015-05-06

UniRxのシンプルなサンプルの取扱説明書
前(ObservableWWW.Get ダウンロード)
UniRxのシンプルなサンプルの取扱説明書 その10(プッシュを遅らせる Delay)

一定時間後に実行

今回はわかりやすいそして何度か出てきているTimerとIntervalを紹介します。
それぞれ一定時間後、一定時間ごとにプッシュしてくれます。
例えばアニメーションとか、なんかそんな感じのものを作るときに便利です。

JavaScriptのsetTimeoutやsetIntervalに近い動作をします。

今回はそれぞれ5秒後に青くなるGameObjectと50msごとに徐々に緑になっていくGameObjectを作ります。

前準備

TimerというTimerSample.csが貼り付けられているGameObject
IntevalというIntevalSample.csが貼り付けられているGameObject

5秒後に青くなる

n秒後に何かを起こしたい場合Timerが便利です。
今回は5秒後にGameObjectを青くします。
コードはこんな感じ

TimerSample.cs
using UnityEngine;
using System.Collections;
using UniRx;
using System;

public class TimerSample : MonoBehaviour {

    // Use this for initialization
    void Start () {
        //5秒たったらプッシュ
        Observable.Timer(TimeSpan.FromSeconds(5)).Subscribe(_ =>
        {
            //青くする
            GetComponent<SpriteRenderer>().color = Color.blue;
        }).AddTo(this);
    }

}

特に難しいところはないと思います。
Observable.Timer(TimeSpan dueTime)
でdueTime後に1度だけ値がプッシュされます。
で、青くしています。

50msごとに徐々に緑に

一定時間ごとに起こしてほしい処理を記述するにはIntervalが便利です。
アニメーションとかをメインの処理と分離できるのでおすすめ。
今回は徐々に緑にしていきます。

IntervalSample.cs
using UnityEngine;
using System.Collections;
using UniRx;
using System;


public class IntevalSample : Base {

    // Use this for initialization
    void Start () {

        //50ms毎に購読する
        Observable.Interval(TimeSpan.FromMilliseconds(50)).Subscribe(l =>
        {
            //緑色に近づける
            GetComponent<SpriteRenderer>().color = Color.Lerp(Color.white, Color.green, l / 200.0f);
        }).AddTo(this);
    }

}

先ほどのTimerがIntervalに変わっただけです。
Observable.Interval(TimeSpan dueTime)
で一定時間ごとにプッシュしてくれます。
プッシュされてくる値は何回目のプッシュかなのでそれを使ってColor.Lerpを使用して色を徐々に変えていきます。

実行結果

というわけでこんなかんじで5秒後に青になるものと緑に近づくものが出来ました。
スクリーンショット 2015-05-06 15.55.39.png

補足

Frame数を数えて同じ動作をするTimerFrameとIntervalFrameもあります。

40
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
40
25