
Unity-MCP Resources 资源参考指南以只读 URI 全面透视 Unity 编辑器状态【免费下载链接】unity-mcpUnity MCP acts as a bridge between AI assistants and your Unity Editor. Give your LLM tools to manage assets, control scenes, edit scripts, and automate tasks within Unity.项目地址: https://gitcode.com/GitHub_Trending/un/unity-mcpUnity-MCP 在 AI 助手与 Unity 编辑器之间充当桥接层工具Tools用于修改资源Resources用于观察。本文是 Unity-MCP 资源系统的完整参考手册覆盖mcpforunity://统一资源标识符URI方案下的编辑器状态、相机、图形、场景与 GameObject、预制体、项目、多实例与测试八大类资源并深入源码层解释其实现机制与分页、URL 编码等关键细节。读完本文你将掌握在动手修改场景之前如何用一行资源 URI 精准读懂 Unity 的任意运行状态形成可靠的先读后写Agent 工作流。本文主体对应仓库内 unity-mcp-skill/references/resources-reference.md并结合 MCPForUnity/Editor/Resources 目录下的 C# 实现与 Server/tests/test_resource_uri_references.py 测试用例进行源码级补充说明。资源模型概述只读的 Unity 状态快照在 Unity-MCP 的架构哲学中资源与工具是两个互补的侧面资源提供对 Unity 状态的只读访问用于检查工具用于修改只有在对场景、对象、配置有了充分认知之后才应调用。官方操作指南unity-mcp-skill/SKILL.md将其概括为 Resource-First Workflow先检查编辑器状态再理解场景然后定位目标最后执行操作并验证结果。所有资源统一采用mcpforunity://协议mcpforunity://{category}/{resource_path}[?query_params]其中category包括editor、scene、prefab、project、pipeline、rendering、menu-items、custom-tools、tests、instances。查询参数query_params用于传递分页游标、instance_id等动态参数。从源码实现看每个资源在 Unity 编辑器侧都是一个标注了[McpForUnityResource]特性的静态类。该特性定义于 MCPForUnity/Editor/Resources/McpForUnityResourceAttribute.cs支持显式指定资源名如get_gameobject也支持将类名从 PascalCase 自动转换为 snake_case例如ManageAsset→manage_asset作为默认资源名从而实现了资源的自动发现与路由。每个 handler 类必须提供公开静态方法HandleCommand(JObject)负责解析参数、执行读取并返回序列化结果。需要特别留意的是资源的名称与其 URI 刻意不同如get_editor_statevsmcpforunity://editor/stateURI 方案无法从名称推导。仓库中的 Server/tests/test_resource_uri_references.py 专门测试了这一点——它扫描服务端指令、资源与工具描述、Unity 工具返回的提示字符串以及 Agent 可见的 Markdown 文档确保凡提及某个资源处必须同时给出完整 URI避免 Agent 拼接出 404 的地址。编辑器状态资源Editor State这类资源回答一个关键问题编辑器现在能用吗在任意复杂工具操作之前读取它们是避免busy错误的第一道防线。mcpforunity://editor/state —— 编辑器就绪快照返回编辑器整体的就绪度快照是执行工具操作前的体检报告{ unity_version: 2022.3.10f1, is_compiling: false, is_domain_reload_pending: false, play_mode: { is_playing: false, is_paused: false }, active_scene: { path: Assets/Scenes/Main.unity, name: Main }, ready_for_tools: true, blocking_reasons: [], recommended_retry_after_ms: null, staleness: { age_ms: 150, is_stale: false } }关键字段语义字段含义使用建议ready_for_tools是否可安全调用工具仅当为true时才继续操作is_compiling是否正在编译为true时等待is_domain_reload_pending是否待执行域重载为true时等待blocking_reasons工具可能失败的原因数组按数组逐项排查recommended_retry_after_ms建议的重试等待毫秒数按此值 sleep 后重试底层实现位于 MCPForUnity/Editor/Resources/Editor/EditorState.cs它只是薄薄一层真正的工作在 MCPForUnity/Editor/Services/EditorStateCache.cs 中完成。这个缓存服务通过[InitializeOnLoad]在编辑器启动时初始化维护一个 schema 为unity-mcp/editor_state2的快照对象并做了大量工程优化1 秒节流更新EditorApplication.update回调以最小 1 秒间隔刷新MinUpdateIntervalSeconds 1.0并在检测到编译边界切换、播放模式切换、域重载等关键事件时立即强制重建快照状态变更前置检测在构建完整 JSON 快照前先用一组廉价检查场景路径、聚焦状态、播放/暂停、资源导入、测试运行、活动阶段判断是否真的发生了变化无变化时直接跳过昂贵的BuildSnapshot()调用避免 GC 尖峰编译误报修正GetActualIsCompiling()用CompilationPipeline.compilationStarted/Finished事件维护的_pipelineCompilationRunning标志修正EditorApplication.isCompiling的已知误报如 Recompile-After-Finished-Playing 导致整个播放会话期间保持true、或LockReloadAssemblies导致锁定期间保持true域重载感知通过AssemblyReloadEvents.beforeAssemblyReload/afterAssemblyReload精确记录域重载时间戳并设置is_domain_reload_pending标志后台重打时间戳当 Unity 退到后台时缓存时间戳会变陈旧此时在GetSnapshot()中重新盖上observed_at_unix_ms确保服务端的陈旧性检查仍能对真正无响应的编辑器生效。mcpforunity://editor/selection —— 当前选中对象返回编辑器当前选中的对象集合可用于理解 Agent 或用户当前的操作上下文{ activeObject: Player, activeGameObject: Player, activeInstanceID: 12345, count: 3, gameObjects: [Player, Enemy, Wall], assetGUIDs: [] }activeInstanceID是后续访问mcpforunity://scene/gameobject/{instance_id}的直接入口assetGUIDs标识选中的非场景资产。mcpforunity://editor/active-tool —— 当前编辑器工具状态返回当前激活的编辑工具移动、旋转、缩放等及其变换设置{ activeTool: Move, isCustom: false, pivotMode: Center, pivotRotation: Global }mcpforunity://editor/windows —— 已打开的编辑器窗口{ windows: [ { title: Scene, typeName: UnityEditor.SceneView, isFocused: true, position: {x: 0, y: 0, width: 800, height: 600} } ] }typeName给出窗口的完整 CLR 类型名如UnityEditor.SceneView可用于判断某个工具窗口Console、Inspector 等当前是否打开。mcpforunity://editor/prefab-stage —— 预制体编辑上下文当编辑者在预制体模式下Prefab Stage编辑某个预制体时返回该上下文信息{ isOpen: true, assetPath: Assets/Prefabs/Player.prefab, prefabRootName: Player, isDirty: false }isOpen指示当前是否处于预制体 StageisDirty指示预制体资产是否有未保存修改。在进行任何预制体编辑前读取此资源可避免在错误的编辑上下文中操作对象。相机资源mcpforunity://scene/cameras用途列出场景中所有相机Unity Camera 与 CinemachineCamera及其完整状态。在调用manage_camera工具创建或配置相机之前先读此资源以了解当前相机布局。{ brain: { exists: true, gameObject: Main Camera, instanceID: 55504, activeCameraName: Cam_Cinematic, activeCameraID: -39420, isBlending: false }, cinemachineCameras: [ { instanceID: -39420, name: Cam_Cinematic, isLive: true, priority: 50, follow: {name: CameraTarget, instanceID: -26766}, lookAt: {name: CameraTarget, instanceID: -26766}, body: CinemachineThirdPersonFollow, aim: CinemachineRotationComposer, noise: CinemachineBasicMultiChannelPerlin, extensions: [] } ], unityCameras: [ { instanceID: 55504, name: Main Camera, depth: 0.0, fieldOfView: 50.0, hasBrain: true } ], cinemachineInstalled: true }关键字段语义brainCinemachineBrain 的状态——当前哪个相机处于激活状态、是否处于混合blend过渡cinemachineCameras所有 CinemachineCamera 组件及其管线信息body/aim/noise 处理器、extensions 扩展列表unityCameras所有原生 Unity Camera 组件的深度depth与视场角FOVcinemachineInstalledCinemachine 包是否可用。在 MCPForUnity/Editor/Resources/Scene/CamerasResource.cs 中该资源直接委托给相机工具模块的CameraControl.ListCameras()实现与manage_camera工具共享同一套序列化逻辑——这正是读与写共用同一数据模型的体现。结合 unity-mcp-skill/SKILL.md 中的相机工具说明Tier 1 的 create/target/lens/priority/list/screenshot 始终可用而 brain、body/aim/noise 管线、混合等 Tier 2 能力依赖com.unity.cinemachine包——读取mcpforunity://scene/cameras可以第一时间确认该包是否已安装。图形资源Graphicsmcpforunity://scene/volumes —— 体积组件与后处理效果用途列出场景中所有 Volume 组件及其效果与参数。在调用manage_graphics的 volume 系列 actionvolume_create、volume_add_effect、volume_set_effect等之前读取。{ pipeline: Universal (URP), volumes: [ { name: PostProcessVolume, instance_id: -24600, is_global: true, weight: 1.0, priority: 0, blend_distance: 0, profile: MyProfile, profile_path: Assets/Settings/MyProfile.asset, effects: [ { type: Bloom, active: true, overridden_params: [intensity, threshold, scatter] }, { type: Vignette, active: true, overridden_params: [intensity, smoothness] } ] } ] }关键字段语义is_global该 Volume 是全局生效还是仅在其碰撞体collider范围内生效effects[].overridden_params哪些参数被显式覆写而非使用默认值——这决定了volume_set_effect应设置哪些参数profile_path内嵌 profile 时为空字符串共享 profile 资产时给出资产路径。其实现位于 MCPForUnity/Editor/Resources/Scene/VolumesResource.cs内部调用图形工具模块的VolumeOps.ListVolumes()与manage_graphics的 volume action 共用同一实现。mcpforunity://rendering/stats —— 渲染性能计数器用途获取当前渲染性能计数器Draw Call、批次、三角形数、显存占用。可与manage_graphics的 stats 系列 actionstats_get、stats_list_counters、stats_get_memory配合用于性能诊断前后的对比。{ draw_calls: 42, batches: 35, set_pass_calls: 12, triangles: 15234, vertices: 8456, dynamic_batches: 5, static_batches: 20, shadow_casters: 3, render_textures: 8, render_textures_bytes: 16777216, visible_skinned_meshes: 2 }实现位于 MCPForUnity/Editor/Resources/Scene/RenderingStatsResource.cs调用RenderingStatsOps.GetStats()。mcpforunity://pipeline/renderer-features —— URP 渲染器特性用途列出当前激活 URP Renderer 上的渲染器特性SSAO、Decals 等并给出其在特性列表中的位置索引——该索引是feature_toggle、feature_remove、feature_configure等操作的目标定位依据。{ rendererDataName: PC_Renderer, features: [ { index: 0, name: ScreenSpaceAmbientOcclusion, type: ScreenSpaceAmbientOcclusion, isActive: true, properties: { m_Settings: Generic } } ] }关键字段语义index特性在列表中的位置供feature_toggle、feature_remove、feature_configure使用isActive特性是否启用rendererDataName当前激活的是哪个 URP Renderer Data 资产。实现位于 MCPForUnity/Editor/Resources/Scene/RendererFeaturesResource.cs调用RendererFeatureOps.ListFeatures()与manage_graphics的 feature 系列 actionfeature_list、feature_add、feature_remove、feature_toggle等共用实现。场景与 GameObject 资源这是资源体系中结构最丰富的一族遵循先文档、再对象、再组件的递进式读取设计。mcpforunity://scene/gameobject-api —— 使用文档入口该资源返回 GameObject 相关资源的完整使用文档是首次接触此功能族时的必读资源。mcpforunity://scene/gameobject/{instance_id} —— 基础数据用途返回 GameObject 的基础数据元数据不含组件属性序列化。instance_id来自find_gameobjects工具的返回结果。{ instanceID: 12345, name: Player, tag: Player, layer: 8, layerName: Player, active: true, activeInHierarchy: true, isStatic: false, transform: { position: [0, 1, 0], rotation: [0, 0, 0], scale: [1, 1, 1] }, parent: {instanceID: 0}, children: [{instanceID: 67890}], componentTypes: [Transform, Rigidbody, PlayerController], path: /Player }实现位于 MCPForUnity/Editor/Resources/Scene/GameObjectResource.cs。从源码看SerializeGameObject()只收集轻量元数据变换数据同时给出局部与全局两种形式position/localPosition、rotation/localRotation、scale/lossyScale、父节点与子节点的 instance ID 列表、以及仅含类型名的componentTypes列表——避免了对每个组件做完整序列化的高昂开销。参数解析还体现了宽容性设计instanceID、instance_id、id三种键名均可接受。mcpforunity://scene/gameobject/{instance_id}/components —— 全量组件分页用途返回 GameObject 上所有组件的完整属性序列化结果支持分页。查询参数参数类型默认值说明instance_idint—GameObject 的 instance IDpage_sizeint25每页数量最大 100cursorint0分页游标include_propertiesbooltrue设为false则只返回类型与 instance ID不含属性{ gameObjectID: 12345, gameObjectName: Player, components: [ { type: Transform, properties: { position: {x: 0, y: 1, z: 0}, rotation: {x: 0, y: 0, z: 0, w: 1} } }, { type: Rigidbody, properties: { mass: 1.0, useGravity: true } } ], cursor: 0, pageSize: 25, nextCursor: null, hasMore: false }源码实现印证了分页细节GameObjectResource.cs 中的GameObjectComponentsResource将page_size通过Mathf.Clamp(pageSize, 1, 100)限制在 1100用Skip(cursor).Take(pageSize)切片并依据游标 本页数量 总数计算nextCursor与hasMore。当include_propertiesfalse时只返回typeName完整命名空间与instanceID显著降低负载。这个先列类型、再按需深入的两步式读取正是处理大型 GameObject 的最佳实践。mcpforunity://scene/gameobject/{instance_id}/component/{component_name} —— 单个组件用途返回单个组件的完整属性。component_name传组件类型名如Rigidbody、Camera、Transform。{ gameObjectID: 12345, gameObjectName: Player, component: { type: Rigidbody, properties: { mass: 1.0, drag: 0, angularDrag: 0.05, useGravity: true, isKinematic: false } } }从源码看GameObjectComponentResource在遍历组件时同时用短类型名GetType().Name与完整类型名GetType().FullName做忽略大小写的匹配因此rigidbody、Rigidbody、UnityEngine.Rigidbody均能命中若匹配失败返回明确错误Component X not found on GameObject Y。预制体资源Prefabmcpforunity://prefab-api —— 使用文档入口返回预制体资源的完整使用文档。mcpforunity://prefab/{encoded_path} —— 预制体资产信息用途返回预制体资产的信息。encoded_path是 URL 编码后的资产路径原始路径URL 编码形式Assets/Prefabs/Player.prefabAssets%2FPrefabs%2FPlayer.prefab即所有/须编码为%2F否则路径段会被 URI 路由解析器误解为路径分隔符。{ assetPath: Assets/Prefabs/Player.prefab, guid: abc123..., prefabType: Regular, rootObjectName: Player, rootComponentTypes: [Transform, PlayerController], childCount: 5, isVariant: false, parentPrefab: null }isVariant指示是否为预制体变体parentPrefab给出变体所基于的父预制体非变体时为null。mcpforunity://prefab/{encoded_path}/hierarchy —— 完整层级用途返回预制体的完整层级结构包含嵌套预制体信息{ prefabPath: Assets/Prefabs/Player.prefab, total: 6, items: [ { name: Player, instanceId: 12345, path: /Player, activeSelf: true, childCount: 2, componentTypes: [Transform, PlayerController] }, { name: Model, path: /Player/Model, isNestedPrefab: true, nestedPrefabPath: Assets/Prefabs/PlayerModel.prefab } ] }当某个层级节点是嵌套预制体实例时会同时给出isNestedPrefab: true与nestedPrefabPath使 Agent 可以顺着嵌套路径继续读取更深层的预制体结构。项目资源Projectmcpforunity://project/info —— 静态项目配置{ projectRoot: /Users/dev/MyProject, projectName: MyProject, unityVersion: 2022.3.10f1, platform: StandaloneWindows64, assetsPath: /Users/dev/MyProject/Assets }该资源常用于检测项目是否启用了 uGUI/TMP/Input System/UI Toolkit 等能力见 unity-mcp-skill/SKILL.md 中 UI 工作流的建议也是unity_reflect/unity_docs等文档类工具判断 API 可用性的依据。mcpforunity://project/tags —— 标签列表返回 TagManager 中定义的全部标签[Untagged, Respawn, Finish, EditorOnly, MainCamera, Player, GameController, Enemy]mcpforunity://project/layers —— 层列表返回全部图层及其索引031{ 0: Default, 1: TransparentFX, 2: Ignore Raycast, 4: Water, 5: UI, 8: Player, 9: Enemy }未定义的层索引如3不会出现在结果中。此资源是manage_gameobject设置layer参数、或manage_physics配置碰撞矩阵collision matrix时的取值依据。mcpforunity://menu-items —— 可用菜单项返回当前所有可用的 Unity 菜单项供execute_menu_item工具调用[ File/New Scene, File/Open Scene, File/Save, Edit/Undo, Edit/Redo, GameObject/Create Empty, GameObject/3D Object/Cube, Window/General/Console ]先读取本资源拿到准确的菜单路径字符串再调用execute_menu_item可避免手写路径与编辑器实际菜单不符导致的失败。该资源的实现位于 MCPForUnity/Editor/Resources/MenuItems/GetMenuItems.cs。mcpforunity://custom-tools —— 项目自定义工具返回当前激活 Unity 项目中可用的自定义工具通过 CustomTools 机制注册{ project_id: MyProject, tool_count: 3, tools: [ { name: capture_screenshot, description: Capture screenshots in Unity, parameters: [ {name: filename, type: string, required: true}, {name: width, type: int, required: false}, {name: height, type: int, required: false} ] } ] }parameters数组给出了每个自定义工具的参数名、类型与必填性是调用自定义工具前的签名表。仓库根目录下的 mcp_source.py 与 CustomTools/RoslynRuntimeCompilation 展示了这类自定义工具机制的典型用法。实例资源Instancemcpforunity://instances —— 运行中的编辑器实例用途列出所有正在运行的 Unity 编辑器实例服务于多实例工作流multi-instance{ transport: http, instance_count: 2, instances: [ { id: MyProjectabc123, name: MyProject, hash: abc123, unity_version: 2022.3.10f1, connected_at: 2024-01-15T10:30:00Z }, { id: TestProjectdef456, name: TestProject, hash: def456, unity_version: 2022.3.10f1, connected_at: 2024-01-15T11:00:00Z } ], warnings: [] }结合set_active_instance(instanceMyProjectabc123)工具使用先读取mcpforunity://instances拿到实例id格式为项目名hash再切换活跃实例之后的所有调用都会路由到该实例。当工具调用静默失败时优先检查是否为实例路由问题。测试资源Testmcpforunity://tests —— 全部测试返回项目中的全部测试Unity Test Framework[ { name: TestSomething, full_name: MyTests.TestSomething, mode: EditMode }, { name: TestOther, full_name: MyTests.TestOther, mode: PlayMode } ]full_name是run_tests工具test_names参数所需的准确名称mode区分 EditMode 与 PlayMode。mcpforunity://tests/{mode} —— 按模式过滤参数mode为EditMode或PlayMode。示例mcpforunity://tests/EditMode只返回 EditMode 测试。典型的测试工作流见 unity-mcp-skill/SKILL.md为读取本资源确定测试名 →run_tests(modeEditMode, test_names[...])异步启动 →get_test_job(job_id..., wait_timeout60)轮询结果。最佳实践资源优先的 Agent 工作流1. 复杂操作前先检查编辑器状态# Before any complex operation: # Read mcpforunity://editor/state # Check ready_for_tools true编译、域重载、播放模式切换、资源导入activity.phase分别对应compiling、domain_reload、playmode_transition、asset_import期间调用工具会返回 busy正确的姿势是轮询editor/state直到ready_for_tools true。2. 采用 Find Then Read 模式# 1. find_gameobjects to get IDs result find_gameobjects(search_termPlayer) # 2. Read resource for full data # mcpforunity://scene/gameobject/{id}find_gameobjects按名称/标签/组件高效返回实例 ID 列表本身负载极小随后用 ID 精确读取单个对象的完整数据避免一次性拉取整棵场景树。3. 大型查询务必分页# Start with include_propertiesfalse for component lists # mcpforunity://scene/gameobject/{id}/components?include_propertiesfalsepage_size25 # Then read specific components as needed # mcpforunity://scene/gameobject/{id}/component/Rigidbody先用include_propertiesfalse拿到组件清单再按需读取单个组件并把page_size控制在 25100 之间响应中的nextCursor用于翻页hasMore为true时继续。4. 预制体路径必须 URL 编码# Wrong: # mcpforunity://prefab/Assets/Prefabs/Player.prefab # Correct: # mcpforunity://prefab/Assets%2FPrefabs%2FPlayer.prefab这是最容易踩的坑路径中的/不编码会与 URI 的路径分段语法冲突导致资源解析失败。5. 始终保持多实例感知# Always check mcpforunity://instances when: # - First connecting # - Commands fail unexpectedly # - Working with multiple projects首次连接、命令意外失败、或同时打开多个 Unity 项目时先读mcpforunity://instances确认当前路由到的编辑器实例。底层机制与质量保障资源系统的三个设计要点值得注意其一工具与资源共享实现。从 CamerasResource.cs、VolumesResource.cs 等文件可以看到资源 handler 直接复用工具模块的ListCameras、ListVolumes、GetStats、ListFeatures等实现。读与写共用同一数据模型保证了资源返回的字段如相机 priority、Volume 的overridden_params与工具接受的参数完全对齐避免 Agent 读到一份数据、写入时却对不上字段名。其二宽容的参数解析。在 GameObjectResource.cs 中instanceID、instance_id、id三种写法均被接受pageSize/page_size、includeProperties/include_properties同理。这与 unity-mcp-skill/SKILL.md 中参数类型约定向量既支持列表也支持 JSON 字符串、布尔值既支持原生布尔也支持字符串一脉相承容忍不同 LLM 的表述习惯。其三URI 一致性有自动化测试兜底。Server/tests/test_resource_uri_references.py 从服务端指令、资源/工具描述、Unity 返回提示、Agent 可见文档四个层面扫描确保任何面向 Agent 的文本在提及资源时都同时给出完整 URI——这保证了本文所描述的所有mcpforunity://地址在真实运行环境中均可解析。结语Unity-MCP 的资源体系为 AI 助手提供了一套只读优先的观察层先读mcpforunity://editor/state确认编辑器可用再通过find_gameobjects与scene/gameobject/{id}精准定位对象用scene/cameras、scene/volumes、rendering/stats、pipeline/renderer-features掌握图形与相机全貌最后才调用工具实施修改并借助project/info、menu-items、custom-tools、instances、tests等资源完成全局导航。这套观察 → 决策 → 行动 → 验证的闭环正是 Agent 在 Unity 编辑器中可靠、可复现地完成自动化任务的基础。更完整的工具参数与工作流模板可继续查阅 unity-mcp-skill/references/tools-reference.md 与 unity-mcp-skill/references/workflows.md。【免费下载链接】unity-mcpUnity MCP acts as a bridge between AI assistants and your Unity Editor. Give your LLM tools to manage assets, control scenes, edit scripts, and automate tasks within Unity.项目地址: https://gitcode.com/GitHub_Trending/un/unity-mcp创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考