Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Attribute that makes a field enable/disable status controlled by a boolean condition
/// <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;
}
@emadkhezri

This comment has been minimized.

Copy link
Owner Author

@emadkhezri emadkhezri commented Sep 7, 2021

ToggleField

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment