Last active
December 3, 2023 02:06
-
-
Save arif-pandu/20901829e0581feae518214006c5be30 to your computer and use it in GitHub Desktop.
Unity Color Option Drawer with AppColor Enum Dictionary
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; | |
using System.Collections.Generic; | |
#region Color Enum | |
enum AppColor | |
{ | |
Custom, | |
White, | |
Red, | |
Green, | |
Blue, | |
Black, | |
} | |
#endregion | |
[CustomPropertyDrawer(typeof(Color))] | |
public class ColorOptionDrawer : PropertyDrawer | |
{ | |
private readonly Dictionary<AppColor, Color> colorOptions; | |
public ColorOptionDrawer() | |
{ | |
colorOptions = new Dictionary<AppColor, Color> | |
{ | |
{ AppColor.Red, new Color(1,0,0,1) }, | |
{ AppColor.Green, new Color(0,1,0,1) }, | |
{ AppColor.Blue, new Color(0,0,1,1) }, | |
{ AppColor.White, new Color(1,1,1,1) }, | |
{ AppColor.Black, new Color(0,0,0,1) } | |
}; | |
} | |
private AppColor selectedColorOption; | |
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) | |
{ | |
EditorGUI.BeginProperty(position, label, property); | |
if (property.propertyType == SerializedPropertyType.Color) | |
{ | |
Rect dropdownPosition = new Rect(position.x, position.y, position.width - 100f, position.height); | |
Color currentColor = property.colorValue; | |
selectedColorOption = DetermineSelectedColorOption(currentColor); | |
selectedColorOption = (AppColor)EditorGUI.EnumPopup(dropdownPosition, label, selectedColorOption); | |
if (selectedColorOption == AppColor.Custom) | |
{ | |
Rect colorFieldPosition = new Rect(position.x + dropdownPosition.width + 5f, position.y, 100f, position.height); | |
property.colorValue = EditorGUI.ColorField(colorFieldPosition, property.colorValue); | |
} | |
else | |
{ | |
if (colorOptions.ContainsKey(selectedColorOption)) | |
{ | |
Color selectedColor = colorOptions[selectedColorOption]; | |
Color selectedEnumColor = colorOptions[selectedColorOption]; | |
property.colorValue = selectedEnumColor; | |
} | |
else | |
{ | |
EditorGUI.LabelField(position, "Invalid Color Option"); | |
} | |
} | |
} | |
else | |
{ | |
EditorGUI.LabelField(position, label.text, "Use AppColorDrawer with a Color field."); | |
} | |
EditorGUI.EndProperty(); | |
} | |
private AppColor DetermineSelectedColorOption(Color color) | |
{ | |
foreach (var kvp in colorOptions) | |
{ | |
if (kvp.Value == color) | |
{ | |
return kvp.Key; | |
} | |
} | |
return AppColor.Custom; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment