unity场景名对象在Inspector面板以下拉列表形式显示,避免输入错误。
首先创建一个类用来获取BuildSetting中场景列表中的所有场景名字
public class MSceneName : PropertyAttribute {
/// <summary>
/// 场景名列表
/// </summary>
public string[] NameList {
get {
return GetAllSceneNames();
}
}
/// <summary>
/// 获取BuildSetting中场景列表,并返回场景名列表
/// </summary>
/// <returns></returns>
public string[] GetAllSceneNames() {
List<string> lst = new List<string>();
foreach (EditorBuildSettingsScene scene in EditorBuildSettings.scenes) {
if (scene.enabled) {
string str = scene.path.Substring(scene.path.LastIndexOf('/') + 1);
str = str.Substring(0, str.Length - 6);
lst.Add(str);
}
}
return lst.ToArray();
}
}
编写Inspector面板显示的扩展方法
[CustomPropertyDrawer(typeof(MSceneName))]
public class MSceneNameInspector : PropertyDrawer {
public MSceneNameInspector() {
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
string[] nameList = (attribute as MSceneName).NameList;
if(property.propertyType == SerializedPropertyType.String) {
int index = Mathf.Max(0, Array.IndexOf<string>(nameList, property.stringValue));
index = EditorGUI.Popup(position, property.displayName, index, nameList);
property.stringValue = nameList[index];
} else {
base.OnGUI(position, property, label);
}
}
}
使用方法,在声明变量前添加特性即可。
[MSceneName] public string sceneForm;