Created
January 21, 2017 17:12
-
-
Save Problematic/54fdf72c7e8ee74633029f32cb3ad24c to your computer and use it in GitHub Desktop.
Rate limiting for Unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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