Skip to content

Instantly share code, notes, and snippets.

@pomeloRHO
Created August 1, 2023 19:12
Show Gist options
  • Save pomeloRHO/08a90fd3ca5f3bb559c1e8240107c379 to your computer and use it in GitHub Desktop.
Save pomeloRHO/08a90fd3ca5f3bb559c1e8240107c379 to your computer and use it in GitHub Desktop.
[Unity] Hide field with property state
using UnityEngine;
/// Adding this attribute to a property will hide according to the property `PropName`'s state
public class HideWithPropertyAttribute : PropertyAttribute {
public string PropName;
public bool HideWhenTrue;
public HideWithPropertyAttribute(string propName, bool hideWhenTrue = false) {
PropName = propName;
HideWhenTrue = hideWhenTrue;
}
}
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(HideWithPropertyAttribute))]
public class HideWithPropertyAttributeDrawer : PropertyDrawer {
SerializedProperty Parent(SerializedProperty property, string name) {
var prop = property.GetParent(false);
prop = prop.FindPropertyRelative(name);
return prop;
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label) {
var attr = attribute as HideWithPropertyAttribute;
var prop = Parent(property, attr.PropName);
if (prop == null) {
return base.GetPropertyHeight(property, label);
}
if (prop.boolValue == attr.HideWhenTrue) {
return 0;
}
return base.GetPropertyHeight(property, label);
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
var attr = attribute as HideWithPropertyAttribute;
var prop = Parent(property, attr.PropName);
if (prop == null) return;
if (prop.boolValue == attr.HideWhenTrue) {
return;
}
position.height = base.GetPropertyHeight(property, label);
EditorGUI.PropertyField(position, property, label);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment