- Home /
Limiting Variables (On Initialisation)
Q. Is there a way to limit variables on initialisation?
Something like:
public var healthLevel : int = Mathf.Clamp(100, 0, 100);
I've tried the above code and my health is definitely going into the minuses with a simple Update() { healthLevel--; }
Answer by Michael La Voie · Mar 24, 2010 at 10:00 PM
Hey Majmuns,
What @KvanteTore was saying is instead of using
function Update(){
healthLevel--;
}
Use something like this:
public var healthLevel : int;
public function ChangeHealth(amount: int) { var newHealth = this.healthLevel + amount; newHealth = Mathf.Clamp(newHealth, 0, 100); this.healthLevel = newHealth; }
function Update(){ ChangeHealth(-1); }
In short, you can't set a limit directly on a variable, but you can use a function to access it, thus respecting your constraints. C# offers formal support for getters and setters, but with UnityScript, you can simulate it quite easily as I suggested. Just make the healthLevel variable private so that the only way to touch it is through ChangeHealth().
Answer by KvanteTore · Mar 24, 2010 at 09:40 PM
Instead of accessing the field healthLevel directly, you might consider creating getter/setter functions enforcing the required conditions.
public var healthLevel : int;
public function SetHealth(level: int) { level = Mathf.Clamp(level, 0, 100); this.healthLevel = level; }