Skip to content

Instantly share code, notes, and snippets.

@TORISOUP
Last active March 11, 2019 00:22
Show Gist options
  • Save TORISOUP/53f9f0c2fff17e1afdbc to your computer and use it in GitHub Desktop.
Save TORISOUP/53f9f0c2fff17e1afdbc to your computer and use it in GitHub Desktop.
押された瞬間&長押しされたら一定間隔で発火する
using System;
using UnityEngine;
using System.Collections;
using UniRx;
using UniRx.Triggers;
using UnityEngine.EventSystems;
public class ObservableButtonLongDownTrigger : ObservableTriggerBase, IPointerDownHandler, IPointerUpHandler
{
private Subject<Unit> onPointerDownSubject;
private Subject<Unit> onPointerUpSubject;
/// <summary>
/// 押した瞬間と、指定フレーム数以上長押しされていた時に一定間隔で発火するObservableを生成する
/// </summary>
/// <param name="repeatStartFrame">長押しの判定フレーム数</param>
/// <param name="repeatSpanFrame">繰り返すフレーム数</param>
/// <returns></returns>
public IObservable<Unit> OnButtonLongDownAsObservable(int repeatStartFrame = 50, int repeatSpanFrame = 10)
{
if (onPointerDownSubject == null)
{
onPointerDownSubject = new Subject<Unit>();
}
if (onPointerUpSubject == null)
{
onPointerUpSubject = new Subject<Unit>();
}
//長押ししていたら発動するストリーム
//InputイベントはUpdateと同期して使うべきなのでUpdateAsObservableを本流にする
var delayStream = this.UpdateAsObservable()
.SkipUntil(onPointerDownSubject.DelayFrame(repeatStartFrame)) //タップされてから指定フレーム経過したら本流を通す
.ThrottleFirstFrame(repeatSpanFrame - 1); //一定間隔にフィルタリングする
//本流のストリーム
return onPointerDownSubject
.Merge(delayStream) // 押された瞬間 + 長押しストリームを合成
.TakeUntil(onPointerUpSubject) //途中で指を離したら終了
.RepeatUntilDestroy(gameObject) //リセット処理
.Publish().RefCount(); //Hot変換
}
protected override void RaiseOnCompletedOnDestroy()
{
if (onPointerDownSubject != null)
{
onPointerDownSubject.OnCompleted();
}
if (onPointerUpSubject != null)
{
onPointerUpSubject.OnCompleted();
}
}
public void OnPointerDown(PointerEventData eventData)
{
if (onPointerDownSubject != null)
{
onPointerDownSubject.OnNext(Unit.Default);
}
}
public void OnPointerUp(PointerEventData eventData)
{
if (onPointerUpSubject != null)
{
onPointerUpSubject.OnNext(Unit.Default);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment