75 lines
2.6 KiB
C#
75 lines
2.6 KiB
C#
using System.Threading.Tasks;
|
|
using MCPForUnity.Editor.Tools;
|
|
using Newtonsoft.Json.Linq;
|
|
using UnityEditor;
|
|
using UnityEngine;
|
|
|
|
namespace UIInfoBuilder
|
|
{
|
|
/// <summary>
|
|
/// MCP 工具:提取 UI Prefab 信息并生成 JSON 文件
|
|
/// AI 可通过 execute_custom_tool 调用此工具
|
|
/// </summary>
|
|
[McpForUnityTool("extract_ui_prefab", Description = "提取 UI Prefab 信息并生成 JSON 文件,用于 AI 理解 UI 结构")]
|
|
public static class ExtractUIPrefabTool
|
|
{
|
|
public static Task<object> HandleCommand(JObject @params)
|
|
{
|
|
string prefabPath = @params?["prefab_path"]?.ToString();
|
|
|
|
// 验证参数
|
|
if (string.IsNullOrEmpty(prefabPath))
|
|
{
|
|
return Task.FromResult<object>(new
|
|
{
|
|
success = false,
|
|
error = "prefab_path 参数不能为空",
|
|
hint = "请提供 Prefab 资源路径,如 Assets/Art_Out/UI/Prefab/xxx.prefab"
|
|
});
|
|
}
|
|
|
|
// 加载 Prefab
|
|
var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(prefabPath);
|
|
if (prefab == null)
|
|
{
|
|
return Task.FromResult<object>(new
|
|
{
|
|
success = false,
|
|
error = $"无法加载 Prefab: {prefabPath}",
|
|
hint = "请确认路径正确且文件存在"
|
|
});
|
|
}
|
|
|
|
try
|
|
{
|
|
// 生成 JSON 文件路径
|
|
string jsonPath = Application.dataPath + "/../ExtractedPrefabs/" + prefab.name + ".json";
|
|
|
|
// 提取 Prefab 信息
|
|
UIInfoExtractor.ExtractPrefab(prefab, jsonPath);
|
|
|
|
// 返回相对路径,便于 AI 读取
|
|
string relativePath = "ExtractedPrefabs/" + prefab.name + ".json";
|
|
|
|
return Task.FromResult<object>(new
|
|
{
|
|
success = true,
|
|
message = $"成功提取 Prefab 信息: {prefab.name}",
|
|
json_path = relativePath,
|
|
absolute_path = jsonPath,
|
|
hint = $"请使用 Read 工具读取 {relativePath} 文件内容,参考 ExtractedPrefabs/README.md 理解 JSON 格式"
|
|
});
|
|
}
|
|
catch (System.Exception ex)
|
|
{
|
|
return Task.FromResult<object>(new
|
|
{
|
|
success = false,
|
|
error = $"提取失败: {ex.Message}",
|
|
hint = "请检查 Prefab 是否有效"
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|