Created
August 1, 2023 19:12
-
-
Save pomeloRHO/08a90fd3ca5f3bb559c1e8240107c379 to your computer and use it in GitHub Desktop.
[Unity] Hide field with property state
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
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; | |
} | |
} |
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
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