Skip to content

Instantly share code, notes, and snippets.

@emadkhezri
Created September 7, 2021 12:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emadkhezri/efe9ada55227cd0416cd7d432d6b67ee to your computer and use it in GitHub Desktop.
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
/// <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
Copy link
Author

ToggleField

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