Skip to content

Instantly share code, notes, and snippets.

@jackyli-work
Created February 29, 2020 07:04
Show Gist options
  • Save jackyli-work/6a2c3b46276a3d543586bef514052c5d to your computer and use it in GitHub Desktop.
Save jackyli-work/6a2c3b46276a3d543586bef514052c5d to your computer and use it in GitHub Desktop.
Selectable Enumeration
using System;
using System.ComponentModel;
using UnityEngine;
using System.Reflection;
namespace JFun.Gameplay.CreateWorld
{
[AttributeUsage(AttributeTargets.Field)]
public class EnumDescriptionAttribute : PropertyAttribute
{
}
public static class EnumExt
{
public static string GetDescription(this Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : value.ToString();
}
public static Enum Next(this Enum value)
{
Array valuerange = Enum.GetValues(value.GetType());
int index = Array.IndexOf(valuerange, value);
index++;
return (Enum)valuerange.GetValue(index < valuerange.Length ? index : valuerange.Length - 1) ;
}
public static Enum Previous(this Enum value)
{
Array valuerange = Enum.GetValues(value.GetType());
int index = Array.IndexOf(valuerange, value);
index--;
return (Enum)valuerange.GetValue(index >= 0 ? index : 0);
}
}
}
using UnityEditor;
using UnityEngine;
using System;
using System.Reflection;
using JFun.Gameplay.CreateWorld.UI;
namespace JFun.Gameplay.CreateWorld
{
[CustomPropertyDrawer(typeof(EnumDescriptionAttribute), true)]
public class ShowReadOnlyDescriptionDrawer : PropertyDrawer
{
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
var height = EditorGUI.GetPropertyHeight(property, label, true);
if (property.propertyType == SerializedPropertyType.Enum)
height *= 2;
return height;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
//if (property.propertyType == SerializedPropertyType.Enum)
{
Enum targetEnum = (Enum)Enum.ToObject(fieldInfo.FieldType, property.intValue);
Enum enumNew = EditorGUI.EnumPopup(position, label.text, targetEnum);
property.enumValueIndex =
(int)Convert.ChangeType(enumNew, targetEnum.GetType());
var height = position.height / 2;
position.y += height;
position.height = height;
//GUI.enabled = false;
EditorGUI.BeginDisabledGroup(true);
EditorGUI.LabelField(position, "Description", enumNew.GetDescription(), GUIStyle.none);
EditorGUI.EndDisabledGroup();
//GUI.enabled = true;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment