I'm making a statistics system for a Unity game and attempting to write some functions that update a given statistic (identified by their field name) with a given value using reflection. I know reflection can be controversial but I thought it would be better practice than exposing the fields containing the statistics structs. The only issue is that the field values don't seem to be actually updating -- printing the before and after field values shows that they remain the same even after these functions are called.
Here's what I've tried for now. _lifetimeStats
is a private static struct which contains various fields holding different statistics. The int is being used on fields which are already defined as ints.
private static LifetimeStatistics _lifetimeStats;
/// <summary>
/// Replaces the current value of the statistic with the provided value.
/// See also: <see cref="UpdateLifetimeStat"/>
/// </summary>
public static void SetLifetimeStat(string statName, object value)
{
var stat = _lifetimeStats.GetType().GetField(statName);
stat.SetValue(_lifetimeStats, value);
}
/// <summary>
/// Adds the provided value to the current value of the statistic.
/// See also: <see cref="SetLifetimeStat"/>
/// </summary>>
public static void UpdateLifetimeStat(string statName, int value)
{
var stat = _lifetimeStats.GetType().GetField(statName);
stat.SetValue(_lifetimeStats, (int)stat.GetValue(_lifetimeStats) + value);
}
And here's a snippet of the LifetimeStats struct:
public struct LifetimeStatistics {
public int TotalMinutesPlayed;
public int TotalNumberOfJumps;
public int TotalNumberOfDeaths;
public int TotalDistanceTraveled;
public int CurrentDailyPlayStreak;
... other fields, constructors, etc...
}
Anyone have an idea of why the field values aren't updating?