Skip to content

Instantly share code, notes, and snippets.

@ryuuguu
Forked from ProGM/ExampleBehavior.cs
Last active June 21, 2023 04:12
Show Gist options
  • Save ryuuguu/cdf71b4fc24b402edd372a449240d4cd to your computer and use it in GitHub Desktop.
Save ryuuguu/cdf71b4fc24b402edd372a449240d4cd to your computer and use it in GitHub Desktop.
A PropertyDrawer to show a popup field with a generic list of string for your Unity3d attribute
using System;
using UnityEngine;
public class ExampleBehavior : MonoBehaviour {
[DropDownList("Cat", "Dog")] public string Animal;
//using a method
[DropDownList(typeof(ExamplePropertyDrawersHelper), "methodExample")]
public string methodExample;
}
public class DropDownList : PropertyAttribute {
public delegate string[] GetStringList();
public DropDownList(params string [] list) {
List = list;
}
public DropDownList(Type type, string methodName) {
var method = type.GetMethod (methodName);
if (method != null) {
List = method.Invoke (null, null) as string[];
} else {
Debug.LogError ("NO SUCH METHOD " + methodName + " FOR " + type);
}
}
public string[] List;
}
using System.Collections.Generic;
using UnityEngine;
public static class ExamplePropertyDrawersHelper {
public static string[] methodExample() {
var temp = new List<string>();
temp.Add("Example");
temp.Add("Second");
return temp.ToArray();
}
}
using System;
using UnityEngine;
using UnityEditor;
//This file should be in an Editor subdirectory
[CustomPropertyDrawer(typeof(DropDownList))]
public class DropDownListDrawer : PropertyDrawer {
public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) {
var stringInList = attribute as DropDownList;
var list = stringInList.List;
if (property.propertyType == SerializedPropertyType.String) {
if (list.Length != 0) {
int index = Mathf.Max(0, Array.IndexOf(list, property.stringValue));
index = EditorGUI.Popup(position, property.displayName, index, list);
property.stringValue = list[index];
}
else {
property.stringValue = "";
}
} else if (property.propertyType == SerializedPropertyType.Integer) {
property.intValue = EditorGUI.Popup (position, property.displayName, property.intValue, list);
} else {
base.OnGUI (position, property, label);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment