5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UniRx:一定間隔(Interval)で発行するObservableを停止・再起動させる。

Posted at

UniRxは便利。
なんだけども、正直学習用の情報が少なく、親切に用意されている物が初心者に見えなかったりする。(まさに私)
UniRxを使ってみて、とりあえず躓いたのが一定間隔(Interval)で発行するObservableを停止させて、任意のタイミングで再起動させること。
とりあえず学習成果のコードは下記。

using UniRx;
using UniRx.Triggers; 
using UnityEngine;

System.IDisposable  hoge_obs;//クラス変数宣言

void Stream_start(int hoge_msec){
      hoge_obs = Observable
      .Interval(System.TimeSpan.FromMilliseconds(hoge_msec))
      .Subscribe(_ =>{
                 //一定間隔で実行する何か   
            });
}

void Stream_stop(){
      hoge_obs.Dispode();
}

void Start(){
//ZONEに侵入しら一定間隔実行開始
      this.OnTriggerEnterAsObservable()
      .Where(x => x.gameObject.tag == "ZONE")
      .Subscribe(_ => {
             Stream_start(100);
             });
//ZONEから出たら停止
      this.OnTriggerExitAsObservable()
      .Where(x => x.gameObject.tag == "ZONE")
      .Subscribe(_ => {
             Stream_stop();
             });
}

Observableをvarで宣言するとローカル関数なので、System.IDisposableとしてクラス変数宣言したところがポイント。
これが出来れば時間を変えながら一定間隔実行できるようになる。動き物を書くときとか大分楽になるはず。

でもやっぱりローカル関数の方が色々安全なのかなと初心者的に思ったりしますが、どうなんでしょうか。
もっと良い方法はある気がする。
あったら誰か教えてください。

5
1
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
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?