On my team’s game http://playadnc.com I’ve created several different gauges for health, mana, shields, and misc… From those I created this master GaugeBase class that’s super useful for rapidly rolling new meter systems. Hopefully this saves someone a chunk of time. Also ideas / thoughts for improvements would be highly appreciated.
using UnityEngine;
using System.Collections;
namespace Adnc.Combat {
/// <summary>
/// A basic re-usable gauge used to create health, mana, shields, ect.
/// </summary>
[System.Serializable]
public abstract class GaugeBase {
[SerializeField] protected int _charge = 0;
/// <summary>
/// The currently available charge.
/// </summary>
/// <value>The charge.</value>
public virtual int Charge {
get { return _charge; }
set { _charge = Mathf.Max(Mathf.Min(value, _chargeMax), 0); }
}
[HideInInspector]
[SerializeField] protected int _chargeMax;
/// <summary>
/// Maximum charge the gauge can hold.
/// </summary>
/// <value>The charge max.</value>
public virtual int ChargeMax {
get { return _chargeMax; }
set {
_chargeMax = value;
if (_charge > _chargeMax) _charge = _chargeMax;
}
}
[Tooltip("How much charge is genereated per minute.")]
public float chargeRegen;
float chargeRegenPool; // Total charge left to distribute
/// <summary>
/// Calculates, finalizes, and sets the maximum value. Should be run upon creation to initialize the gauge.
/// </summary>
public virtual void Setup () {
_chargeMax = _charge;
}
/// <summary>
/// Adds the charge up the the ChargeMax value
/// </summary>
/// <param name="val">Value.</param>
public virtual void ReceiveCharge (int val) {
Charge += val;
}
/// <summary>
/// Removes the charge. If the requested amount of charge is available.
/// </summary>
/// <returns><c>true</c>, if charge was removed, <c>false</c> otherwise.</returns>
/// <param name="charge">Charge.</param>
public virtual void RemoveCharge (int charge) {
Charge -= charge;
}
/// <summary>
/// Checks if the passed amount of charge is available.
/// </summary>
/// <returns><c>true</c> if this instance is charge the specified val; otherwise, <c>false</c>.</returns>
/// <param name="val">Value.</param>
public virtual bool IsCharge (int val) {
return val <= _charge;
}
/// <summary>
/// Checks if the charge is full.
/// </summary>
/// <returns><c>true</c> if this instance is full; otherwise, <c>false</c>.</returns>
public virtual bool IsFull () {
return _charge == _chargeMax;
}
/// <summary>
/// Force set the charge and max charge. Should be called with caution as it circumvents charge caps.
/// </summary>
/// <param name="charge">Charge.</param>
public virtual void SetCharge (int charge) {
this._charge = charge;
this._chargeMax = charge;
}
/// <summary>
/// Makes charge generate or decay points over time. Designed to be called in the update loop.
/// </summary>
public virtual void ChargeRegen () {
int addCharge;
chargeRegenPool += chargeRegen / 60f * Time.deltaTime;
if (chargeRegenPool > 1f) {
addCharge = (int)Mathf.Floor(chargeRegenPool);
ReceiveCharge(addCharge);
chargeRegenPool -= addCharge;
} else if (chargeRegenPool < -1f) {
addCharge = (int)Mathf.Ceil(chargeRegenPool);
ReceiveCharge(addCharge);
chargeRegenPool -= addCharge;
}
}
}
}
Your encapsulation looks a bit weird. Everything is public, including your backing _charge variable. But you also have getters and setters for accessing this variable. You also hide some members from the inspector, like _maxCharge, that would often be set directly from the inspector.
You should also look at making your code a little more self documenting. SetCharge should be SetChargeAndMaxCharge. And so forth.
You should also have a lower charge limit, as it is I can drain the charge down far past zero.
RemoveCharge and RecieveCharge could also be combined into a single method. Adding a negative number is the same as subtracting.
Setup automatically turns the current charge into the max to prevent confusion of setting two different values.
Variables with _ are technically private, but I left them public for ease of access when writing a parent class.
SetChargeAndMaxCharge feels like a bit of a long title. It is verbose and specific though.
Actually Charge will prevent you from draining things below 0 (unless I’m missing something).
I originally had add and receive in one method, but was easier with my code base to keep them separate. Mainly because I was putting a ton of (x * -1f) which was mucking up the code base and hurting maintainability.
There is no hard and fast rule about it, anything that gets the job done.
But some further thoughts anyway.
Any reason this is not a constructor?
Technically private will be ignored at some stage, introducing hard to fix bugs, and general spaghettiness. (You are already using an _ variable directly inside of RecieveCharge.) Coding by convention is fine. But proper encapsulation is better.
Maybe. I was a little puzzled as to why you would need this method. But if it makes sense for your specific mechanics then go ahead.
I missed this. In that case there is no need to do the max checking inside of RecieveCharge.
Fair enough comment. You may want to deal with the case where a negative variable is passed in. Currently someone could add in a negative charge. Not a huge deal now, but it might be if the methods diverge.
My 2 cents - some overlap with BoredMormon but I’ll restate anyways.
‘Protected’ allows for manipulation of the variables in inherited classes without exposing them to the world like ‘public’ will. Private is still preferable since you have Properties to access everything, but protected is a good compromise.
I would also make _chargeMax settable in the inspector and not forcibly set by your Setup method. I can think of many bars that want to start empty and raise to a max (most Rage/Fury mechanics), in which case your _charge would want to be 0 but your _chargeMax would want to be a different number.
Speaking of Rage/Fury (Or hunger, battery, some types of shields - lots of examples) - Those bars drain over time instead of fill, which is not supported currently, unless I am missing something.
If you add a negative number currently via ReceiveCharge, you can dip below zero. ReceiveCharge should use the Charge property, not the _charge backing field, just like RemoveCharge does.
Potential ideas to expand upon - Raising events for emptying or filling a bar. Makes it easier to hook in death for health bars, shieldbreak effects, or ‘Fully charged’ effects.
This is definitely a useful thing to have, given the many different bars that exist.
Setup is overridable, so it could easily be adjusted for your mentioned use case
With a few tweaks ChargeRegen could easily support a negative value to simulate decay. Will adjust base class to reflect your cool idea.
Woops, you have a good point on Receive charge (fixing in base class)
@Kiwasi About the constructor I’ve had some issues with Unity running the constructor then applying serialization after. Which would overwrite the values in setup (at least that happened to me in the past). Maybe I missed something though and that isn’t an issue anymore.