Unity小实用六-Unity编辑中的字符串下拉框(String Dropdown)
在Unity中,enum类型会默认转换为下拉框进行选择。但是在平常的使用中,有时候还是非常不方便,我想要字符串作为选择呢?
找Unity官方的方法,没有找到,那就自己进行进行定制了。
第一步:需要我们定义一个自己的StringInList属性。然后增加到Inspector中可以进行编辑。文件名为: StringInListDrawer.cs代码如下:
using System;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class StringInList : PropertyAttribute
{
public delegate string[] GetStringList();
public StringInList(params string[] list)
{
List = list;
}
public StringInList(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
{
get;
private set;
}
}
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(StringInList))]
public class StringInListDrawer : PropertyDrawer
{
// Draw the property inside the given rect
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var stringInList = attribute as StringInList;
var list = stringInList.List;
if (property.propertyType == SerializedPropertyType.String)
{
int index = Mathf.Max(0, Array.IndexOf(list, property.stringValue));
index = EditorGUI.Popup(position, property.displayName, index, list);
property.stringValue = list[index];
}
else if (property.propertyType == SerializedPropertyType.Integer)
{
property.intValue = EditorGUI.Popup(position, property.displayName, property.intValue, list);
}
else
{
base.OnGUI(position, property, label);
}
}
}
#endif
第二步:我们需要支持自定义类型,并初始化选择框的所有值。这个文件,你可以自定义自己的方法。我举个例子,文件名为: PropertyDrawersHelper.cs。代码如下:
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public static class PropertyDrawersHelper
{
#if UNITY_EDITOR
public static string[] AllSceneNames()
{
var temp = new List<string>();
foreach (UnityEditor.EditorBuildSettingsScene S in UnityEditor.EditorBuildSettings.scenes)
{
if (S.enabled)
{
string name = S.path.Substring(S.path.LastIndexOf('/') + 1);
name = name.Substring(0, name.Length - 6);
temp.Add(name);
}
}
return temp.ToArray();
}
#endif
}
最后,开始演示一下这个功能了,举个例子,代码如下所示:
public class MyBehavior : MonoBehaviour
{
// This will store the string value
[StringInList("Cat", "Dog")] public string Animal;
// This will store the index of the array value
[StringInList("John", "Jack", "Jim")] public int PersonID;
// Showing a list of loaded scenes
[StringInList(typeof(PropertyDrawersHelper), "AllSceneNames")] public string SceneName;
}
结果如下:
这样就很好的满足了我的需求,字符串下拉框,比直接使用enum更能满足我的要求。