Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@snaka
Created October 15, 2014 06:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snaka/819ea18c7e372121b01a to your computer and use it in GitHub Desktop.
Save snaka/819ea18c7e372121b01a to your computer and use it in GitHub Desktop.
PlayerPrefsをGenericにする試み ref: http://qiita.com/snaka/items/a54bea3c553d60f8b98d
public class AppConfig<T> where T: IConvertible {
string key;
T defaultValue;
public AppConfig(string key, T defaultValue) {
this.key = key;
this.defaultValue = defaultValue;
if (!typeof(T).Equals (typeof(Int32)) &&
!typeof(T).Equals (typeof(String)) &&
!typeof(T).Equals (typeof(Single)) &&
!typeof(T).Equals (typeof(Boolean))) {
throw new NotSupportedException("specified type of T (" + typeof(T) + ") is not supported.");
}
}
public string Key {
get {
return key;
}
}
public T Value {
set {
if (value.GetType ().Equals (typeof(string))) {
Debug.Log ("set string : " + value);
PlayerPrefs.SetString (key, value.ToString ());
} else if (value.GetType ().Equals (typeof(int))) {
Debug.Log ("set int : " + value);
PlayerPrefs.SetInt (key, value.ToInt32 (CultureInfo.CurrentCulture));
} else if (value.GetType().Equals(typeof(float))) {
PlayerPrefs.SetFloat(key, value.ToSingle(CultureInfo.CurrentCulture));
} else if (value.GetType().Equals(typeof(bool))) {
// true なら 1 、false なら 0 に置き換える
PlayerPrefs.SetInt(key, value.ToBoolean(CultureInfo.CurrentCulture) ? 1 : 0);
}
}
get {
object value = default(T);
Debug.Log (typeof(T));
if (typeof(T).Equals (typeof(String))) {
value = PlayerPrefs.GetString (key, defaultValue.ToString ());
Debug.Log ("string : " + value);
} else if (typeof(T).Equals (typeof(Int32))) {
value = PlayerPrefs.GetInt (key, defaultValue.ToInt32 (CultureInfo.CurrentCulture));
Debug.Log ("int : " + value);
} else if (value.GetType ().Equals (typeof(T))) {
value = PlayerPrefs.GetFloat(key, defaultValue.ToSingle(CultureInfo.CurrentCulture));
} else if (value.GetType().Equals(typeof(T))) {
// true なら 1 、false なら 0 に置き換える
var def = defaultValue.ToBoolean(CultureInfo.CurrentCulture) ? 1 : 0;
value = (PlayerPrefs.GetInt(key, def) == 1);
}
return (T)Convert.ChangeType(value, typeof(T));
}
}
public void Delete() {
PlayerPrefs.DeleteKey(key);
}
}
AppConfig<string> m_configStr = new AppConfig<string>("Test.Config", "hoge");
AppConfig<int> m_configInt = new AppConfig<int>("Test.Config.Int", -1);
AppConfig<float> m_configFloat = new AppConfig<float>("Test.Config.Float", -1.11f);
AppConfig<bool> m_configBool = new AppConfig<bool>("Test.Config.BoolTrue", false);
m_configStr.Value = "test";
m_configInt.Value = 100;
m_configFloat.Value = 9.99f;
m_configBool.Value = true;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment