덴바의 노트

[유니티] 버튼 연타 방지 확장 메소드 구현 본문

프로그래밍 노트

[유니티] 버튼 연타 방지 확장 메소드 구현

덴바 2026. 5. 27. 11:45

 

오늘의 키워드
  • UniRx
  • 연타 방지

 

버튼 연속 클릭 방지 코드

 

 

public static IObservable<Unit> OnClickAsObservableWithThrottle(
  this Button button, float intervalSeconds, Action onWaitAction = null)
{
  var cooldownEnd = DateTimeOffset.MinValue;
  return button.OnClickAsObservable()
    .Do(_ => {
      if (DateTimeOffset.UtcNow < cooldownEnd)
        onWaitAction?.Invoke(); // 대기 중 액션 실행
    })
    .Where(_ => {
      var now = DateTimeOffset.UtcNow;
      if (now < cooldownEnd) return false; // 쿨다운 중 차단
      cooldownEnd = now.AddSeconds(intervalSeconds);
      return true;
    }).AsUnitObservable();
}​