7
5

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.

キー入力、マウス入力をIObservable<T>に変換して使う

Last updated at Posted at 2019-08-26

#はじめに

キー入力ってUpdateに

if(Input.GetKey(KeyCode.A)){
    //なんかの処理
}

とか
UniRxを使うときは

Observable.EveryUpdate()
          .Where(_ => Input.GetKey(KeyCode.A))
          .Subscribe(_ => {
              //なんかの処理
          });

this.UpdateAsObservable()
    .Where(_ => Input.GetKey(KeyCode.A))
    .Subscribe(_ => {
        //なんかの処理
    });

みたいな感じだと思います。(?)
UniRxを使う場合はEveryUpdate等をいくつも書くことになって不便です。
ということで専用のストリームソースを作れるようにしました。

#InputをIObservableとして扱う
##用意するもの
UniRx
https://github.com/euglenach/InputAsObservable

##概要
対応しているメソッドは以下のものになります

  • GetKey,GetKeyDown,GetKeyUp
  • anyKey,anyKeyDown
  • Axis,AxisRaw
  • GetMouseButton,GetMouseButtonDown,GetMouseButtonUp
  • GetButton,GetButtonDown.GetButtonUp

##書き方

名前空間: UniRx.Triggers

###静的メソッド

InputAsObservable.GetKey(KeyCode.A).Subscribe(_ => Debug.Log("key:A")); //GetKey 

InputAsObservable.AnyKey.Subscribe(_ => Debug.Log("anyKey")); //anykey

InputAsObservable.Axis("Vertical").Subscribe(y => Debug.Log("Axis y:" + y)); //Axis

InputAsObservable.GetMouseButton(0).Subscribe(_ => Debug.Log("mouse0")); //GetMouseButton

###Componentの拡張メソッド

this.OnKeyAsObservable(KeyCode.D).Subscribe(_ => Debug.Log("key:D")); //GetKey 

this.OnAnyKeyAsObservable().Subscribe(_ => Debug.Log("anyKey")); //anykey

this.OnAxisAsObservable("Vertical").Subscribe(y => Debug.Log("Axis:" + y)); //Axis

こっちは、ComponentがDestroyすると自動で購読がDisposeされます。

#更新履歴
・2019/09/07 GetButton系メソッドにも対応しました

7
5
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?