Skip to content

Instantly share code, notes, and snippets.

@fangzhangmnm
Created January 9, 2026 07:01
Show Gist options
  • Select an option

  • Save fangzhangmnm/85a9297d7af049be072586516c99f358 to your computer and use it in GitHub Desktop.

Select an option

Save fangzhangmnm/85a9297d7af049be072586516c99f358 to your computer and use it in GitHub Desktop.
/**********
Hides a field in the inspector in Unity3D according to the value of a boolean or enum field.
Warning: Code is blind-generated by AI without human inspection, use at your own risk.
Usage:
// Show 'myField' only when 'isEnabled' is true
public bool isEnabled;
[ConditionalField("isEnabled")]
public int myField;
// Show 'myField' only when 'myEnum' == MyEnum.Option2
public enum MyEnum { Option1, Option2, Option3 }
public MyEnum myEnum;
[ConditionalField("myEnum", 1)] // 1 is the index of Option2
public int myField;
Author: chatgpt.com
Supervisor: fangzhangmnm, Jan.9 2026
License: MIT
**********/
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class ConditionalFieldAttribute : PropertyAttribute
{
public string condition;
public int enumIndex; // used when condition is an enum
public bool useEnum;
public bool inverse;
// Bool condition constructor (keeps your old behavior)
public ConditionalFieldAttribute(string condition, bool inverse = false)
{
this.condition = condition;
this.inverse = inverse;
this.useEnum = false;
}
// Enum condition constructor (show when enum == enumIndex)
public ConditionalFieldAttribute(string condition, int enumIndex, bool inverse = false)
{
this.condition = condition;
this.enumIndex = enumIndex;
this.inverse = inverse;
this.useEnum = true;
}
}
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(ConditionalFieldAttribute))]
public class ConditionalFieldDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
if (ShouldShow(property))
EditorGUI.PropertyField(position, property, label, true);
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return ShouldShow(property) ? EditorGUI.GetPropertyHeight(property, label, true) : 0f;
}
private bool ShouldShow(SerializedProperty property)
{
var condAttr = (ConditionalFieldAttribute)attribute;
var conditionProp = property.serializedObject.FindProperty(condAttr.condition);
if (conditionProp == null) return true; // fail open, or change to false if you prefer
bool enabled;
if (condAttr.useEnum)
{
// Compare by enum *index* (works fine for typical enums like yours: 0,1,2...)
enabled = (conditionProp.propertyType == SerializedPropertyType.Enum)
&& (conditionProp.enumValueIndex == condAttr.enumIndex);
}
else
{
enabled = (conditionProp.propertyType == SerializedPropertyType.Boolean)
&& conditionProp.boolValue;
}
if (condAttr.inverse) enabled = !enabled;
return enabled;
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment