Skip to content

Instantly share code, notes, and snippets.

@SvDvorak
Created February 16, 2016 18:23
Show Gist options
  • Save SvDvorak/f6a84545296b3aa0c041 to your computer and use it in GitHub Desktop.
Save SvDvorak/f6a84545296b3aa0c041 to your computer and use it in GitHub Desktop.
Example for how to create stacked settings
public class SettingsComponent : IComponent
{
public CombinedSettings Settings;
public float Speed { get { return Settings.GetFloat("Speed"); } }
}
public class CombinedSettings
{
private readonly List<Settings> _settingsList = new List<Settings>();
public void AddSettings(Settings settings)
{
_settingsList.Add(settings);
}
public float GetFloat(string key)
{
return _settingsList
.Where(settings => settings.HasValue(key))
.Sum(settings => settings.GetValue<float>(key));
}
public void UpdateTime(float timePassed)
{
foreach (var settings in _settingsList)
{
settings.DecreaseTime(timePassed);
}
_settingsList.RemoveAll(x => !x.HasTimeLeft);
}
}
public class Settings
{
private float _timeLeft;
private readonly Dictionary<string, object> _settings = new Dictionary<string, object>();
public bool HasTimeLeft { get { return _timeLeft > 0; } }
public Settings SetTimeLeft(float timeLeft)
{
_timeLeft = timeLeft;
return this;
}
public Settings AddSetting(string key, object value)
{
_settings.Add(key, value);
return this;
}
public void DecreaseTime(float timePassed)
{
_timeLeft -= timePassed;
}
public T GetValue<T>(string key)
{
return (T)_settings[key];
}
public bool HasValue(string key)
{
return _settings.ContainsKey(key);
}
}
// Add settings
var settings = _pool.CreateEntity().settings.Settings;
settings.AddSettings(new Settings()
.SetTimeLeft(10f)
.AddSetting("Speed", 5)
.AddSetting("Damage", 8));
settings.AddSettings(new Settings()
.SetTimeLeft(4)
.AddSetting("Danger", 11)
.AddSetting("Damage", 122));
// in some settings update system
settings.UpdateTime(Time.deltaTime);
// Use settings
var bulletSpeed = settings.GetFloat("Speed"); // will be 5
var damage = settings.GetFloat("Damage"); // will be 20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment