Skip to content

Instantly share code, notes, and snippets.

@eral
Last active January 30, 2022 23:32
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eral/773d2b289200528d1216 to your computer and use it in GitHub Desktop.
Save eral/773d2b289200528d1216 to your computer and use it in GitHub Desktop.
Enum Mask Property Drawer
// (C) 2014 ERAL
// Distributed under the Boost Software License, Version 1.0.
// (See copy at http://www.boost.org/LICENSE_1_0.txt)
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
[CustomPropertyDrawer(typeof(EnumMaskAttribute))]
public class EnumMaskPropertyDrawer : PropertyDrawer {
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
if (SerializedPropertyType.Enum == property.propertyType) {
object current = GetCurrent(property);
if (null != current) {
EditorGUI.BeginChangeCheck();
var value = EditorGUI.EnumMaskField(position, label, (System.Enum)current);
if (EditorGUI.EndChangeCheck()) {
property.intValue = System.Convert.ToInt32(value);
}
}
} else {
EditorGUI.LabelField(position, label, new GUIContent("This type has not supported."));
}
}
private static object GetCurrent(SerializedProperty property) {
object result = property.serializedObject.targetObject;
var property_names = property.propertyPath.Replace(".Array.data", ".").Split('.');
foreach (var property_name in property_names) {
var parent = result;
var indexer_start = property_name.IndexOf('[');
if (-1 == indexer_start) {
var binding_flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic;
result = parent.GetType().GetField(property_name, binding_flags).GetValue(parent);
} else if (parent.GetType().IsArray) {
var indexer_end = property_name.IndexOf(']');
var index_string = property_name.Substring(indexer_start + 1, indexer_end - indexer_start - 1);
var index = int.Parse(index_string);
var array = (System.Array)parent;
if (index < array.Length) {
result = array.GetValue(index);
} else {
result = null;
break;
}
} else {
throw new System.MissingFieldException();
}
}
return result;
}
}
#endif
public class EnumMaskAttribute : PropertyAttribute {
}
// Created by ERAL
// This is free and unencumbered software released into the public domain.
using UnityEngine;
using System.Collections;
public class Sample : MonoBehaviour {
[EnumMask]
public Flags m_Flags;
[System.Flags]
public enum Flags {
foo = 1<<0,
bar = 1<<1,
baz = 1<<2,
qux = 1<<3,
}
}
@eral
Copy link
Author

eral commented Aug 30, 2014

Can be used to struct & array & private field.

@explosivose
Copy link

Thanks for this it's very useful. Just a hint to anyone else using it: with the unity inspector in debug mode this is disabled or something. Took me ages to figure that one out!

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