I have a simple game where you try to go as high up with rockets as possible. I currently store 2 statistics about your playthrough:
- Current altitude
- Highest altitude
These statistics are stored in a Dictionary<string,float>
where the string key is the name of the statistic. I have two tasks related to stats, setting the statistic, which I do as follows:
public class UpdateAltitude : View
{
public float AltitudeFactor
{
get
{
return altitudeFactor;
}
set
{
altitudeFactor = value;
}
}
[Inject]
public IDictionary<string, float> Stats
{
get;
set;
}
[SerializeField]
private float altitudeFactor;
// Update is called once per frame
private void Update()
{
var altitude = AltitudeFactor * transform.position.y;
Stats["altitude"] = altitude;
Stats["maxaltitude"] = Mathf.Max(Stats["maxaltitude"], altitude);
}
}
View
here is a baseclass from the StrangeIOC framework that allows me to inject into Unity behaviours. The SerializeField
attribute allows me to display the private field in the editor for an artist to use (Unity cannot display properties, so this is a common workaround).
The Stats dictionary is created and injected into my View
instances from a StrangeIOC context like so:
var stats = new Dictionary<string, float>()
{
{"altitude", 0f},
{"maxaltitude", 0f}
};
injectionBinder.Bind<IDictionary<string, float>>().ToValue(stats).ToSingleton();
The other task, displaying the statistic, is done thusly:
public class StatLabel : View
{
public string FormatString
{
get
{
return formatString;
}
set
{
formatString = value;
}
}
[Inject]
public IDictionary<string, float> Stats
{
get;
set;
}
[SerializeField]
private string statName;
public string StatName
{
get
{
return statName;
}
set
{
statName = value;
}
}
[SerializeField]
private string formatString;
private UILabel label;
protected override void Start()
{
base.Start();
label = GetComponent<UILabel>();
}
private void Update()
{
label.text = string.Format(FormatString, Stats[StatName]);
}
}
Here a UILabel
is essentially a TextBlock
control from the NGUI framework.
My issue is that in order for an artist to work with this within the Unity Framework, they need knowledge of the exact string keys in this dictionary, an enum would be a preferable solution, because they appear in the Unity editor as a combo box of possible options, however this would couple my StatLabel
class to this game's enum, and each new game would require a custom version.
I intend soon to add additional statistics, such as speed, max speed, coins, etc, so would like to know if I can improve the existing code to make it more artist-friendly, and reusable, while keeping it extensible.