Last active
March 24, 2020 17:46
-
-
Save Kalinovych/1cd04f8cdbf82211b2499bdd207140e2 to your computer and use it in GitHub Desktop.
[Unity3D Editor] PropertyDrawer for [EnumFlag] attribute - draws an expandable vertical column of toggle buttons filled by your Enum names.
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(EnumFlagAttribute))] | |
public class EnumFlagDrawer : PropertyDrawer | |
{ | |
private static bool foldout = false; | |
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) | |
{ | |
position.height = 16f; | |
foldout = EditorGUI.Foldout( position, foldout, label ); | |
if (foldout) | |
{ | |
int buttonsIntValue = 0; | |
int enumLength = property.enumNames.Length; | |
bool[] buttonPressed = new bool[enumLength]; | |
float buttonsLeft = position.x + EditorGUIUtility.labelWidth; | |
float buttonWidth = position.width - EditorGUIUtility.labelWidth; | |
float buttonHeight = EditorGUIUtility.singleLineHeight; | |
EditorGUI.LabelField( new Rect( position.x, position.y, EditorGUIUtility.labelWidth, position.height ), label ); | |
EditorGUI.BeginChangeCheck(); | |
position.height = buttonHeight * enumLength; | |
for (int i = 0; i < enumLength; i++) | |
{ | |
// Check if the button is/was pressed | |
if ((property.intValue & (1 << i)) == 1 << i) | |
{ | |
buttonPressed[i] = true; | |
} | |
Rect buttonPos = new Rect( buttonsLeft, 16f + position.y + i * buttonHeight, buttonWidth, buttonHeight ); | |
buttonPressed[i] = GUI.Toggle( buttonPos, buttonPressed[i], property.enumNames[i], "Button" ); | |
if (buttonPressed[i]) | |
buttonsIntValue += 1 << i; | |
} | |
if (EditorGUI.EndChangeCheck()) | |
{ | |
property.intValue = buttonsIntValue; | |
} | |
} | |
} | |
public override float GetPropertyHeight(SerializedProperty property, GUIContent label) | |
{ | |
return base.GetPropertyHeight( property, label ) + | |
(foldout | |
? EditorGUIUtility.singleLineHeight * property.enumNames.Length | |
: 0f); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment