マウスのダブルクリックを検知したかったり、あるキーを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);
}
}