Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Problematic
Created January 21, 2017 17:12
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 Problematic/54fdf72c7e8ee74633029f32cb3ad24c to your computer and use it in GitHub Desktop.
Save Problematic/54fdf72c7e8ee74633029f32cb3ad24c to your computer and use it in GitHub Desktop.
Rate limiting for Unity
using UnityEngine;
[CreateAssetMenu (menuName = "Problematic/Rate Limiter")]
public class RateLimiter : ScriptableObject
{
[SerializeField]
float capacity;
[SerializeField]
float fillRate;
TokenBucket tokenBucket;
void OnEnable ()
{
tokenBucket = new TokenBucket (capacity, fillRate);
}
public float Tokens {
get {
return tokenBucket.Tokens;
}
}
public bool Consume (float count)
{
return tokenBucket.Consume (count);
}
}
using UnityEngine;
[System.Serializable]
public class TokenBucket
{
[SerializeField]
float capacity;
[SerializeField]
[Tooltip ("Tokens per second added to the bucket")]
float fillRate;
float tokens = 0;
float timestamp = 0;
public float Tokens {
get {
if (tokens < capacity) {
float now = Time.time;
var delta = fillRate * (now - timestamp);
tokens = Mathf.Min (capacity, tokens + delta);
timestamp = now;
}
return tokens;
}
}
public TokenBucket (float capacity, float fillRate)
{
this.capacity = capacity;
this.fillRate = fillRate;
timestamp = Time.time;
}
public bool Consume (float count)
{
if (Tokens >= count) {
tokens -= count;
return true;
}
return false;
}
public override string ToString ()
{
return string.Format ("[TokenBucket: capacity={0}, fillRate={1}, tokens={2}, timestamp={3}]", capacity, fillRate, tokens, timestamp);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment