Created
September 7, 2021 12:24
-
-
Save emadkhezri/efe9ada55227cd0416cd7d432d6b67ee to your computer and use it in GitHub Desktop.
Attribute that makes a field enable/disable status controlled by a boolean condition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Attribute that makes a field enable/disable status controlled by a boolean condition | |
/// </summary> | |
public class ToggleFieldAttribute : PropertyAttribute { | |
/// <summary> | |
/// Boolean field to control the enable/disable status | |
/// </summary> | |
public readonly string ConditionalField; | |
public ToggleFieldAttribute(string field) { | |
ConditionalField = field; | |
} | |
} | |
//Drawer | |
[CustomPropertyDrawer(typeof(ToggleFieldAttribute))] | |
public class ToggleFieldPropertyDrawer : PropertyDrawer { | |
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { | |
var toggleAttribute = (ToggleFieldAttribute) attribute; | |
var conditionField = property.serializedObject.FindProperty(toggleAttribute.ConditionalField); | |
var toggle = true; | |
if (conditionField.propertyType == SerializedPropertyType.Boolean) { | |
toggle = conditionField.boolValue; | |
} | |
GUI.enabled = toggle; | |
EditorGUI.PropertyField(position, property, label); | |
GUI.enabled = true; | |
} | |
} | |
//Example | |
public class ExampleComponent : MonoBehaviour { | |
public bool TextEnable; | |
[ToggleField("TextEnable")] public string text; | |
} |
Author
emadkhezri
commented
Sep 7, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment