I’m looking for a way to create enumerations with special symbols. And the easiest way I’ve found to create a list or Popup from Inspector has been: Property Drawers in Unity 4.
But, this code:
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour {
[Popup ("Warrior", "Mage", "Archer", "Ninja")]
public string @class = "Warrior";
}
It throws the following errors:
I have installed 4.5.1f3 Unity version. Any solution?
[SOLVED]
Enumeration class, type to define enumerations from items field:
using UnityEngine;
public class Enumeration{
public static readonly string[] items;
}
//Example 1
public class CameraResolutions : Enumeration{
public static readonly new string[] items = new string[]{ "Free Aspect","5:4","4:3","3:2","16:10","16:9" };
}
//Example 2
public class Fraction4 : Enumeration{
public static readonly new string[] items = new string[]{ "1\\4","2\\4","3\\4","4\\4" };
}
PropertyAttribute class, with class type and string params constructor:
using UnityEngine;
public class Enum : PropertyAttribute{
public readonly string[] items;
public int selected = 0;
public Enum(System.Type type){
if (type.IsSubclassOf(typeof(Enumeration)))
{
System.Reflection.FieldInfo fieldInfo = type.GetField("items");
this.items = (string[])fieldInfo.GetValue (null);
} else {
this.items = new string[]{"Assign Enumeration Type"};
}
}
public Enum(params string[] enumerations){ this.items = enumerations; }
}
PropertyDrawer class, in Editor folder, to create popup list:
using UnityEngine;
using UnityEditor;
[CustomPropertyDrawer (typeof (Enum))]
public class EnumDrawer : PropertyDrawer {
Enum enumeration{ get{ return (Enum)attribute; } }
bool Start = true;
public override void OnGUI (Rect position, SerializedProperty prop, GUIContent label) {
if(Start){
Start = false;
for(int i=0;i<enumeration.items.Length;i++){
if(enumeration.items[i].Equals(prop.stringValue)){
enumeration.selected = i;
break;
}
}
}
enumeration.selected = EditorGUI.Popup(EditorGUI.PrefixLabel(position, label),enumeration.selected,enumeration.items);
prop.stringValue = enumeration.items[enumeration.selected];
}
}
Script Test:
using UnityEngine;
public class EnumerationTest : MonoBehaviour {
[Enum("Free Aspect","5:4","4:3","3:2","16:10","16:9")]
public string cameraResolution = "3:2";
[Enum("1\\4","2\\4","3\\4","4\\4")]
public string fraction;
[Enum(typeof(CameraResolutions))]
public string camResolution;
[Enum(typeof(Fraction4))]
public string frac="4\\4";
void Start(){
Debug.Log(cameraResolution);
Debug.Log(fraction);
Debug.Log(camResolution);
Debug.Log(frac);
}
}