// Animancer // https://kybernetik.com.au/animancer // Copyright 2018-2023 Kybernetik //
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
namespace Animancer.Editor
{
/// [Editor-Only]
/// A simple wrapper around to get and set a bool.
///
/// If you are interested in a more comprehensive pref wrapper that supports more types, you should check out
/// Inspector Gadgets - Auto Prefs.
///
/// https://kybernetik.com.au/animancer/api/Animancer.Editor/BoolPref
///
public class BoolPref
{
/************************************************************************************************************************/
/// The prefix which is automatically added before the .
public const string KeyPrefix = nameof(Animancer) + "/";
/// The identifier with which this pref will be saved.
public readonly string Key;
/// The label to use when adding a function to toggle this pref to a menu.
public readonly string MenuItem;
/// The starting value to use for this pref if none was previously saved.
public readonly bool DefaultValue;
/************************************************************************************************************************/
private bool _HasValue;
private bool _Value;
/// The current value of this pref.
public bool Value
{
get
{
if (!_HasValue)
{
_HasValue = true;
_Value = EditorPrefs.GetBool(Key, DefaultValue);
}
return _Value;
}
set
{
if (_Value == value &&
_HasValue)
return;
_Value = value;
_HasValue = true;
EditorPrefs.SetBool(Key, value);
}
}
/// Returns the current value of the `pref`.
public static implicit operator bool(BoolPref pref) => pref.Value;
/************************************************************************************************************************/
/// Creates a new .
public BoolPref(string menuItem, bool defaultValue)
: this(null, menuItem, defaultValue) { }
/// Creates a new .
public BoolPref(string keyPrefix, string menuItem, bool defaultValue)
{
MenuItem = menuItem + " ?";
Key = KeyPrefix + keyPrefix + menuItem;
DefaultValue = defaultValue;
}
/************************************************************************************************************************/
/// Adds a menu function to toggle the of this pref.
public void AddToggleFunction(GenericMenu menu)
{
menu.AddItem(new GUIContent(MenuItem), Value, () =>
{
Value = !Value;
});
}
/************************************************************************************************************************/
/// Returns a string containing the and .
public override string ToString() => $"{nameof(BoolPref)} ({nameof(Key)} = '{Key}', {nameof(Value)} = {Value})";
/************************************************************************************************************************/
}
}
#endif