67 lines
2.2 KiB
C#

using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System;
using LitJson;
using UnityEngine.SceneManagement;
namespace FSM
{
#if UNITY_EDITOR
// 自定义属性抽屉,用于渲染下拉框
[CustomPropertyDrawer(typeof(DropdownStringAttribute))]
public class DropdownStringDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
// 获取自定义属性
DropdownStringAttribute dropdownAttribute = (DropdownStringAttribute)attribute;
// 读取文件并获取选项
string[] options = ReadOptionsFromFile(dropdownAttribute.filePath);
// 显示下拉框
int selectedIndex = Array.IndexOf(options, property.stringValue);
if (selectedIndex == -1)
{
selectedIndex = 0; // 如果没有找到匹配的项,则默认选择第一个选项
}
selectedIndex = EditorGUI.Popup(position, label.text, selectedIndex, options);
// 更新字段值
if (selectedIndex >= 0)
{
property.stringValue = options[selectedIndex];
}
}
// 读取文件并返回选项列表
private string[] ReadOptionsFromFile(string filePath)
{
if (string.IsNullOrEmpty(filePath))
{
return null;
}
List<string> str = new();
string folder = "";
List<JsonData> data = JsonMapper.ToObject<List<JsonData>>(Resources.Load<TextAsset>(filePath).text);
for (int i = 0; i < data.Count; i++)
{
if (SceneManager.GetActiveScene().name == data[i]["scene"].ToString())
{
folder = data[i]["folder"].ToString();
}
}
List<JsonData> data2 = JsonMapper.ToObject<List<JsonData>>(Resources.Load<TextAsset>(folder + "/ExcelData/ExcelToJson/StateData").text);
for (int i = 0; i < data2.Count; i++)
{
if (!string.IsNullOrEmpty(data2[i]["state"].ToString()))
{
str.Add(data2[i]["state"].ToString());
}
}
return str.ToArray();
}
}
#endif
}