LoginSignup
7

More than 3 years have passed since last update.

posted at

UniRxでボタンの長押しを検知

概要

何番煎じだ? って感じなのですが、ネットのサンプルがなんかいまいちほしいやつじゃないので書きます。

  • ボタンを押している間のOnNextの間隔を指定したい
  • ボタンを離した瞬間を取得したい
  • Observableを一時変数にとっておいたりしないで一発でさくっと書きたい

コード

間隔:Update

_button.OnPointerDownAsObservable()
    .SelectMany(_ => _button.UpdateAsObservable())
    .TakeUntil(_button.OnPointerUpAsObservable())
    .DoOnCompleted(() =>
    {
        Debug.Log("released!");
    })
    .RepeatUntilDestroy(_button)
    .Subscribe(unit =>
    {
        Debug.Log("pressing...");
    });

間隔:1秒

_button.OnPointerDownAsObservable()
    .SelectMany(_ => Observable.Interval(TimeSpan.FromSeconds(1)))
    .TakeUntil(_button.OnPointerUpAsObservable())
    .DoOnCompleted(() =>
    {
        Debug.Log("released!");
    })
    .RepeatUntilDestroy(_button)
    .Subscribe(time =>
    {
        Debug.Log("pressing..." + time);
    });

おまけ:ポインターの出入りを検知

_button.OnPointerEnterAsObservable()
    .SelectMany(_ => Observable.Interval(TimeSpan.FromSeconds(1)))
    .TakeUntil(_button.OnPointerExitAsObservable())
    .DoOnCompleted(() =>
    {
        Debug.Log("out");
    })
    .RepeatUntilDestroy(_button)
    .Subscribe(time =>
    {
        Debug.Log("in");
    });

まとめ

SelectManyの引数に与えるオペレータを変えれば間隔は如何様にもできます。
ButtonDestroyされたときにもDoOnCompletedが来ちゃうので、それが困る場合はDoOnCompletedを追加しないでOnPointerUpAsObservableを別に追加してください。

参考

【Unity】【UniRx】TakeXxx系のオペレータまとめ
【Unity】【UniRx】Repeat系のオペレータまとめ

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
What you can do with signing up
7