Skip to content

Instantly share code, notes, and snippets.

@binouze
Last active January 23, 2024 06:32
Show Gist options
  • Save binouze/5cb1923dafc09ec853ac21bad41c4e97 to your computer and use it in GitHub Desktop.
Save binouze/5cb1923dafc09ec853ac21bad41c4e97 to your computer and use it in GitHub Desktop.
Simple CustomPropertyDrawer to show/hide properties based on an Enum or Boolean value
using System;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
[CustomPropertyDrawer( typeof(TestProp))]
public class TestPropDrawerUIE : PropertyDrawer
{
public override VisualElement CreatePropertyGUI( SerializedProperty property )
{
// Create foldout for sub-properties
var container = new Foldout{text = property.displayName};
// Create fields
var FieldBool1 = new PropertyField(property.FindPropertyRelative( "Bool1" ));
var FieldFloat1 = new PropertyField(property.FindPropertyRelative( "Float1" ));
var FieldInt1 = new PropertyField(property.FindPropertyRelative( "Int1" ));
var FieldMyEnum1 = new PropertyField(property.FindPropertyRelative( "MyEnum1" ));
var FieldString1 = new PropertyField(property.FindPropertyRelative( "String1" ));
var FieldListe1 = new PropertyField(property.FindPropertyRelative( "Liste1" ));
// Add fields to the container.
container.Add(FieldBool1);
container.Add(FieldFloat1);
container.Add(FieldInt1);
container.Add(FieldMyEnum1);
container.Add(FieldString1);
container.Add(FieldListe1);
// Register change callback on boolean field
FieldBool1.RegisterCallback<ChangeEvent<bool>>( e =>
{
// Toggle visibility as needed
var visible_style = e.newValue ?
new StyleEnum<DisplayStyle>(DisplayStyle.Flex) :
new StyleEnum<DisplayStyle>(DisplayStyle.None);
FieldFloat1.style.display = visible_style;
FieldInt1.style.display = visible_style;
});
// Register change callback on an enum field
// Enum fields changes are typed as string
FieldMyEnum1.RegisterCallback<ChangeEvent<string>>( e =>
{
// so we need to parse the value
if( Enum.TryParse(e.newValue, out MyEnum coucou) )
{
// Toggle visibility as needed
var visible_style = coucou == MyEnum.ABC ?
new StyleEnum<DisplayStyle>(DisplayStyle.Flex) :
new StyleEnum<DisplayStyle>(DisplayStyle.None);
FieldString1.style.display = visible_style;
FieldListe1.style.display = visible_style;
}
});
return container;
}
}
#endif
public enum MyEnum
{
ABC = 0,
DEF = 1
}
[Serializable]
public class TestProp
{
// bool driven properties
public bool Bool1;
// these properties are shown only if Bool1 = true
public float Float1;
public int Int1;
// enum driven properties
public MyEnum MyEnum1;
// these properties are shown only if MyEnum1 = MyEnum.ABC
public string String1;
public List<int> Liste1;
}
@binouze
Copy link
Author

binouze commented Jan 23, 2024

Note that it uses the UIToolkit implementation and won't work with IMGUI

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