LoginSignup
4
1

More than 3 years have passed since last update.

UniRx で特定の期間にx回入力があったときに購読するヘルパーを作ってみた

Last updated at Posted at 2020-03-17

マウスのダブルクリックを検知したかったり、あるキーを3回押したときだけデバッグモードの画面表示したかったりしませんか?
UniRx で簡単にダブルクリックなどを検知できますが、回数や検知期間を設定できるヘルパー関数を作ってみました。
これでいつでも簡単にデバッグ画面が開けます。

ヘルパー関数

using System;
using System.Collections.Generic;
using UniRx;

public class UniRxHelper
{
    public static IObservable<IList<long>> InputCountDetection(Func<bool> input, int count = 2, int waiting = 200)
    {
        var stream = Observable.EveryUpdate().Where(_ => input());
        var throttle = stream.Throttle(TimeSpan.FromMilliseconds(waiting));
        return stream.Buffer(throttle).Where(i => i.Count >= count);
    }
}

仕様

  • 検知したいイベント、回数、検知が成立する期間を設定することができます。
  • 回数と検知期間を設定しなかった場合、2回、200ms以内に発生したときに、イベントが発行されるようになっています。

使用例

マウスの左ボタンのクリックが、3回、500ms以内に、押されたことを検知して、ログを表示する例です。(面白くなくてすいません)

using UniRx;
using UnityEngine;

public class MouseInput : MonoBehaviour
{
    void Start()
    {
        UniRxHelper
            .InputCountDetection(() => Input.GetMouseButtonDown(0), 3, 500)
            .Subscribe(_ => Debug.Log("トリプルクリックを検知しました。"))
            .AddTo(this);
    }
}

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