using UnityEngine;
using UnityEditor;
#if UNITY_EDITOR
// 自定义属性绘制器,用于自定义属性SceneNameAttribute的绘制
[CustomPropertyDrawer(typeof(SceneNameAttribute))]
public class SceneNameDrawer : PropertyDrawer
{
int sceneIndex = -1;
GUIContent[] sceneNames;
readonly string[] scenePathSplit = { "/", ".unity" };
// 在Inspector中绘制属性
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
// 如果场景数量为0,则返回
if (EditorBuildSettings.scenes.Length == 0) return;
// 如果场景索引为-1,则获取场景名数组
if (sceneIndex == -1)
{
GetSceneNameArray(property);
}
int oldIndex = sceneIndex;
// 绘制下拉框,并更新选择的场景索引
sceneIndex = EditorGUI.Popup(position, label, sceneIndex, sceneNames);
// 如果选择的场景索引发生改变,则更新属性值
if (oldIndex != sceneIndex)
property.stringValue = sceneNames[sceneIndex].text;
}
// 获取场景名数组
private void GetSceneNameArray(SerializedProperty property)
{
// 获取编辑器中的构建设置中的场景数组
var scenes = EditorBuildSettings.scenes;
// 初始化场景名数组
sceneNames = new GUIContent[scenes.Length];
// 遍历场景数组,获取场景名并赋值给场景名数组
for (int i = 0; i < sceneNames.Length; i++)
{
string path = scenes[i].path;
var splitPath = path.Split(scenePathSplit, System.StringSplitOptions.RemoveEmptyEntries);
string sceneName = "";
if (splitPath.Length > 0)
{
sceneName = splitPath[splitPath.Length - 1];
}
else
{
sceneName = "(Deleted Scene)";
}
sceneNames[i] = new GUIContent(sceneName);
}
// 如果场景名数组长度为0,则显示提示信息
if (sceneNames.Length == 0)
{
sceneNames = new[] { new GUIContent("Check Your Build Settings") };
}
// 如果属性值不为空,则尝试匹配对应的场景索引
if (!string.IsNullOrEmpty(property.stringValue))
{
bool nameFound = false;
// 遍历场景名数组,寻找匹配的场景名
for (int i = 0; i < sceneNames.Length; i++)
{
if (sceneNames[i].text == property.stringValue)
{
sceneIndex = i;
nameFound = true;
break;
}
}
// 如果未找到匹配的场景名,则默认选择第一个场景
if (nameFound == false)
{
sceneIndex = 0;
}
}
else
{
sceneIndex = 0;
}
// 更新属性值为选择的场景名
property.stringValue = sceneNames[sceneIndex].text;
}
}
#endif
=====================================================
using UnityEngine;
public class SceneNameAttribute : PropertyAttribute
{
}
=====================================================
[SceneName]
public string startScenName = string.Empty;
``
Unity编辑器拓展:属性拓展-----下拉框
最新推荐文章于 2024-05-31 10:54:37 发布