Skip to content

Instantly share code, notes, and snippets.

@ikriz
Forked from ChemiKhazi/EnumFlagAttribute.cs
Last active February 24, 2017 10:27
Show Gist options
  • Save ikriz/b0f9d96205629e19859e to your computer and use it in GitHub Desktop.
Save ikriz/b0f9d96205629e19859e to your computer and use it in GitHub Desktop.
Unity3d property drawer for automatically making enums flags into mask fields in the inspector.
Unity3d property drawer for automatically making enums flags into mask fields in the inspector.
Usage: Put the .cs files somewhere in your project. When you have an enum field you want to turn into a mask field in the inspector, add the EnumFlag attribute over the field. Eg:
[EnumFlag]
MyCustomEnum thisEnum;
// This lets you give the field a custom name in the inspector.
[EnumFlag("Custom Inspector Name")]
MyCustomEnum anotherEnum;
using UnityEngine;
public class EnumFlagAttribute : PropertyAttribute
{
public string enumName;
public EnumFlagAttribute() {}
public EnumFlagAttribute(string name)
{
enumName = name;
}
}
using System;
using System.Reflection;
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(EnumFlagAttribute))]
public class EnumFlagDrawer : PropertyDrawer {
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EnumFlagAttribute flagSettings = (EnumFlagAttribute)attribute;
Enum targetEnum = (Enum)Enum.ToObject(fieldInfo.FieldType, property.intValue);
GUIContent propName = new GUIContent(flagSettings.enumName);
if (string.IsNullOrEmpty(flagSettings.enumName))
propName = label;
EditorGUI.BeginProperty(position, label, property);
Enum enumNew = EditorGUI.EnumMaskField(position, propName, targetEnum);
property.intValue = (int)Convert.ChangeType(enumNew, fieldInfo.FieldType);
EditorGUI.EndProperty();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment