namespace UnityEditor.SettingsManagement
{
///
/// A settings repository backed by the UnityEditor.EditorPrefs class.
///
public class UserSettingsRepository : ISettingsRepository
{
static string GetEditorPrefKey(string key)
{
return GetEditorPrefKey(typeof(T).FullName, key);
}
static string GetEditorPrefKey(string fullName, string key)
{
return fullName + "::" + key;
}
static void SetEditorPref(string key, T value)
{
var k = GetEditorPrefKey(key);
if (typeof(T) == typeof(string))
EditorPrefs.SetString(k, (string)(object)value);
else if (typeof(T) == typeof(bool))
EditorPrefs.SetBool(k, (bool)(object)value);
else if (typeof(T) == typeof(float))
EditorPrefs.SetFloat(k, (float)(object)value);
else if (typeof(T) == typeof(int))
EditorPrefs.SetInt(k, (int)(object)value);
else
EditorPrefs.SetString(k, ValueWrapper.Serialize(value));
}
static T GetEditorPref(string key, T fallback = default(T))
{
var k = GetEditorPrefKey(key);
if (!EditorPrefs.HasKey(k))
return fallback;
var o = (object)fallback;
if (typeof(T) == typeof(string))
o = EditorPrefs.GetString(k, (string)o);
else if (typeof(T) == typeof(bool))
o = EditorPrefs.GetBool(k, (bool)o);
else if (typeof(T) == typeof(float))
o = EditorPrefs.GetFloat(k, (float)o);
else if (typeof(T) == typeof(int))
o = EditorPrefs.GetInt(k, (int)o);
else
return ValueWrapper.Deserialize(EditorPrefs.GetString(k));
return (T)o;
}
///
/// What SettingsScope this repository applies to.
///
///
public SettingsScope scope
{
get { return SettingsScope.User; }
}
///
/// An identifying name for this repository. User settings are named "EditorPrefs."
///
public string name
{
get { return "EditorPrefs"; }
}
///
/// File path to the serialized settings data.
///
///
/// This property returns an empty string.
///
///
public string path
{
get { return string.Empty; }
}
///
/// Save all settings to their serialized state.
///
///
public void Save()
{
}
///
///
/// Set a value for key of type T.
///
/// The settings key.
/// The value to set. Must be serializable.
/// Type of value.
public void Set(string key, T value)
{
SetEditorPref(key, value);
}
///
///
/// Get a value with key of type T, or return the fallback value if no matching key is found.
///
/// The settings key.
/// If no key with a value of type T is found, this value is returned.
/// Type of value to search for.
public T Get(string key, T fallback = default(T))
{
return GetEditorPref(key, fallback);
}
///
///
/// Does the repository contain a setting with key and type.
///
/// The settings key.
/// The type of value to search for.
/// True if a setting matching both key and type is found, false if no entry is found.
public bool ContainsKey(string key)
{
return EditorPrefs.HasKey(GetEditorPrefKey(key));
}
///
///
/// Remove a key value pair from the settings repository.
///
///
///
public void Remove(string key)
{
EditorPrefs.DeleteKey(GetEditorPrefKey(key));
}
}
}