Skip to content

Instantly share code, notes, and snippets.

@samermurad
Created March 28, 2022 22:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samermurad/351e35a75387b25e45491d6ea94987bc to your computer and use it in GitHub Desktop.
Save samermurad/351e35a75387b25e45491d6ea94987bc to your computer and use it in GitHub Desktop.
RateLimiter for various purposes
class RateLimiter {
public int fps = 100;
public bool isActive = true;
private float? timer = null;
public RateLimiter(int fps, bool immediate = false) {
this.fps = fps;
if (immediate) this.Invalidate();
else this.Reset();
}
// invaliding RateLimiter makes it fire on next check
public bool Invalidate() {
this.timer = 0;
return false;
}
// resetting the RateLimiter makes it wait it the next execution time frame
public bool Reset() {
// assigning the timer to null will make the CanFire assign the initial time to the timer, limiting the rate
this.timer = null;
return false;
}
public bool CanFire(float? time = null) {
if (!this.isActive) return false; // inactive
// allow optional custom time to be dictated from outside
float timeToUse = time.HasValue ? time.Value : Time.time;
// assign the timer either to itself (case present), or assign it to the dictated time
// this will allow us to await the next fire-able tick
this.timer = this.timer.HasValue ? this.timer.Value : timeToUse;
return (timeToUse - this.timer) > ( 1 / this.fps);
}
public bool Fire(float? time = null) {
if (this.CanFire(time)) {
this.Reset();
return true;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment