Unity MCP 场景对象检索实战:深入解析 find_gameobjects 工具的多维搜索与分页机制
Unity MCP 场景对象检索实战:深入解析 find_gameobjects 工具的多维搜索与分页机制
导读
find_gameobjects 是 Unity MCP 中面向"场景对象查找"场景的专用搜索工具,允许 LLM/AI 助手按名称、标签、图层、组件类型、层级路径或实例 ID 六种方式检索场景中的 GameObject,并以分页形式仅返回轻量级的实例 ID 列表。本文以该项目官方工具参考文档为主体,结合 服务端实现 与 Unity 编辑器侧实现 的源码细节,完整讲解其参数语义、六种搜索方式的底层行为、分页游标约定、返回值结构,以及与 GameObject 资源(mcpforunity://scene/gameobject/{id})和 manage_gameobject 的职责分工,帮助读者在 Unity MCP 自动化工作流中正确、高效地完成"先定位、再读取、后操作"的完整链路。
1. 工具定位:轻量搜索,拒绝大载荷
find_gameobjects 被设计为聚焦型搜索工具(focused search tool)。与 manage_gameobject(创建/修改/删除)和 GameObject 资源(读取完整数据)不同,它的唯一职责是:在场景中找出符合条件的 GameObject,并只返回它们的实例 ID 列表。
这一设计动机在服务端与编辑器侧的文档注释中均有明确说明:返回仅含实例 ID 可以最小化传输载荷(minimize payload size),避免在一次搜索中把大量对象的完整数据塞进 MCP 响应(参见 find_gameobjects.py 中的模块与函数文档 和 FindGameObjects.cs 的类注释)。
其定位可总结为:
| 能力 | 工具/资源 | 说明 |
|---|---|---|
| 搜索并返回实例 ID | find_gameobjects |
分页、轻量、只读搜索 |
| 读取单个对象完整数据 | mcpforunity://scene/gameobject/{id} |
名称、标签、图层、Transform、组件类型列表 |
| 读取全部组件(含属性) | mcpforunity://scene/gameobject/{id}/components |
分页支持 |
| 读取单个组件 | mcpforunity://scene/gameobject/{id}/component/{name} |
完整属性序列化 |
| 创建/修改/删除对象 | manage_gameobject |
CRUD 操作 |
职责边界:如果目标是"改对象",不要用
find_gameobjects,直接走manage_gameobject;如果目标是"查对象的详细信息",find_gameobjects只负责第一步拿 ID,后续数据通过资源 URI 获取。这一协作关系在资源文档资源mcpforunity://scene/gameobject-api(见 gameobject.py)中被明确描述为find_gameobjects → resources的两步工作流。
2. 参数详解:schema、默认值与类型宽松化
官方工具参考文档给出了五个参数的元信息,结合服务端源码可得到完整语义:
| 参数 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
search_term |
str |
是 | 无 | 要搜索的值(名称、标签、图层名、组件类型或路径) |
search_method |
Literal['by_name', 'by_tag', 'by_layer', 'by_component', 'by_path', 'by_id'] |
否 | "by_name" |
搜索方式 |
include_inactive |
bool | str | None |
否 | None(→ False) |
是否包含未激活对象 |
page_size |
int | str | None |
否 | None(→ 50) |
每页结果数,默认 50,最大 500 |
cursor |
int | str | None |
否 | None(→ 0) |
分页游标(下一页偏移量),0 基 |
2.1 search_term:唯一必填参数
服务端在进入任何 I/O 之前会先做必填校验——如果 search_term 为空,直接返回错误提示(find_gameobjects.py)。编辑器侧同样要求 searchTerm 或兼容旧版命名的 target 至少提供一个(FindGameObjects.cs),因此早期集成中使用 target 的调用方依然可以工作。
2.2 类型宽松化(coercion)
include_inactive、page_size、cursor 三个参数都允许传入字符串或数字。服务端在发送给 Unity 之前通过 coerce_bool / coerce_int 统一转换:
include_inactive = coerce_bool(include_inactive, default=False)
page_size = coerce_int(page_size, default=50)
cursor = coerce_int(cursor, default=0)
这意味着 LLM 调用时写成 "true"、"10" 这类字符串也会被正确归一化。这一行为在集成测试中被专门覆盖:test_find_gameobjects_boolean_coercion 验证 include_inactive="true" 会被转换为布尔 True 并写入请求参数(test_find_gameobjects.py);test_find_gameobjects_pagination_params 验证字符串形式的 page_size="10"、cursor="20" 被转换为整数(同上 L84-L120)。
2.3 发送到 Unity 的参数命名
服务端组装请求时统一使用 camelCase 参数名发送给编辑器:
params = {
"searchMethod": search_method,
"searchTerm": search_term,
"includeInactive": include_inactive,
"pageSize": page_size,
"cursor": cursor,
}
(find_gameobjects.py,其中 None 值会被过滤掉)
3. 六种搜索方式:底层实现与行为差异
编辑器侧 GameObjectLookup.SearchGameObjects 是搜索的核心实现(GameObjectLookup.cs),六种方式各有其底层行为与限制:
3.1 by_name:精确名称匹配
遍历场景中所有对象,按 go.name == name 做完全相等匹配(非模糊/子串匹配),见 SearchByName。同名对象会全部返回。
3.2 by_tag:标签匹配
默认调用 Unity 的 GameObject.FindGameObjectsWithTag(tag);当 include_inactive=True 时需要手动遍历全部对象并 CompareTag,因为 Unity 的标签查找 API 不会命中未激活对象(SearchByTag)。若标签不存在,会抛出 UnityException 并被捕获后静默返回空结果。
3.3 by_layer:图层匹配(名称或数字)
search_term 既可以传图层名称(通过 LayerMask.NameToLayer 解析),也可以直接传 0~31 的图层编号(SearchByLayer)。非法图层名或越界编号不会报错,只会返回空列表。
3.4 by_component:组件类型匹配
search_term 传组件类型名(如 "Camera"、"Rigidbody")。类型解析委托给 UnityTypeResolver.ResolveComponent,会在已加载的程序集中查找类型(FindComponentType)。若类型找不到,会写入一条警告日志并返回空结果。匹配使用 GetComponent(componentType),即该组件只需存在即可命中(SearchByComponent)。
3.5 by_path:层级路径匹配
路径使用 / 分隔的层级结构,如 Canvas/Panel/Button。匹配规则为"全路径相等或以 /路径 结尾"(MatchesPath),因此支持"相对后缀路径"。
这里有一个值得注意的 Unity API 限制处理(SearchByPath):
- Prefab Stage(预制体编辑模式)下:
GameObject.Find(path)不可用,改用GetAllSceneObjects手动遍历并做路径匹配; - 普通场景下、且
include_inactive=False:直接调用GameObject.Find(path),但该 API 只能找到激活对象; include_inactive=True:退化为手动遍历全部对象匹配路径。
3.6 by_id:实例 ID 直接解析
search_term 传整数形式的实例 ID,通过 InstanceIDToObjectCompat 解析为对象;若对象存在且满足激活条件则返回该 ID(ById 分支)。这是六种方式中唯一"精确命中单个对象"的搜索。
3.7 共同底座:GetAllSceneObjects
除 by_id 与默认路径分支外,多数搜索都依赖 GetAllSceneObjects 遍历场景(GetAllSceneObjects)。它有两个来源:
- Prefab Stage:使用
PrefabStageUtility.GetCurrentPrefabStage()的prefabContentsRoot作为根; - 普通场景:使用
SceneManager.GetActiveScene().GetRootGameObjects()逐层深度优先遍历(GetObjectAndDescendants)。
因此,find_gameobjects 在预制体编辑模式下同样可用,且 include_inactive=False 时遍历过程会跳过未激活子树(if (!includeInactive && !obj.activeInHierarchy) yield break;)。
4. 分页机制:page_size、cursor 与游标语义
4.1 统一的分页契约
编辑器侧使用标准的 PaginationRequest / PaginationResponse<T>(Pagination.cs),它与场景中其他分页工具(如组件资源分页)保持一致。
请求端 PaginationRequest.FromParams(Pagination.cs):
- 同时接受
page_size与pageSize两种命名; - 游标同时接受
cursor(0 基)与page_number/pageNumber(1 基,自动换算为(pageNumber - 1) * pageSize); - 默认
PageSize = 50。
响应端 PaginationResponse<T>.Create(Pagination.cs):
- 游标越界会被钳制到
[0, totalCount]; - 计算
nextCursor:还有下一页时为endIndex,否则为null; HasMore直接由NextCursor.HasValue推导。
4.2 编辑器侧的强制上限
FindGameObjects.HandleCommand 在解析分页后会用 Mathf.Clamp(pagination.PageSize, 1, 500) 把每页大小钳制在 1~500 之间(FindGameObjects.cs),与 Python 侧 schema 中"默认 50、最大 500"的声明一致。
4.3 返回值结构
成功时 find_gameobjects 返回:
{
"success": true,
"message": "Found GameObjects",
"data": {
"instanceIDs": [12345, 67890],
"pageSize": 50,
"cursor": 0,
"nextCursor": 50,
"totalCount": 132,
"hasMore": true
}
}
字段说明(对应 FindGameObjects.cs 与 Pagination.cs):
| 字段 | 含义 |
|---|---|
instanceIDs |
本页命中的实例 ID 列表 |
pageSize |
本页实际大小 |
cursor |
当前页游标(0 基) |
nextCursor |
下一页游标;null 表示已到末页 |
totalCount |
全部命中数(跨页总计) |
hasMore |
是否还有下一页 |
服务端拿到 Unity 响应后会透传 message 与 data 字段(find_gameobjects.py),异常路径统一返回 {"success": false, "message": ...}。
4.4 翻页示例
# 第一页
page1 = find_gameobjects(search_term="Enemy", search_method="by_tag", page_size=50)
# page1["data"]["nextCursor"] == 50, hasMore == True
# 第二页:把上一页的 nextCursor 作为 cursor 传入
page2 = find_gameobjects(search_term="Enemy", search_method="by_tag",
page_size=50, cursor=page1["data"]["nextCursor"])
5. 与 GameObject 资源的协同:ID 即索引
工具文档明确指出:拿到实例 ID 后,用资源 URI 读取详细数据。项目提供三个参数化资源(gameobject.py):
| 资源 URI | 返回内容 |
|---|---|
mcpforunity://scene/gameobject/{id} |
基本数据:instanceID、name、tag、layer、layerName、active、isStatic、transform、parent、children、componentTypes、path |
mcpforunity://scene/gameobject/{id}/components |
全部组件完整属性序列化,支持 page_size(默认 25)、cursor、include_properties 分页参数 |
mcpforunity://scene/gameobject/{id}/component/{name} |
指定类型名的单个组件,如 .../component/Camera |
官方示例(见 gameobject.py 中的资源文档):
mcpforunity://scene/gameobject/-81840
mcpforunity://scene/gameobject/-81840/components
mcpforunity://scene/gameobject/-81840/component/Camera
推荐的标准三步工作流(项目 Skill 文档中的 "Resource-First Workflow",见 unity-mcp-skill/SKILL.md):
1. Check editor state → mcpforunity://editor/state
2. Understand the scene → mcpforunity://scene/gameobject-api
3. Find what you need → find_gameobjects 或 resources
4. Take action → manage_gameobject / create_script / script_apply_edits ...
5. Verify results → read_console, manage_camera(action="screenshot"), resources
实践建议(Skill 模板提示,SKILL.md):模板示例可能因 Unity 版本、UGUI/TMP/Input System 等包配置而异,在使用任何工具修改目标之前,先通过资源和
find_gameobjects校验目标与组件是否存在,并把名称、枚举值视为需适配的占位符。
6. 实战调用模式
6.1 六种搜索方式快速对照
# 按名称(精确匹配)
find_gameobjects(search_term="Player", search_method="by_name")
# 按标签
find_gameobjects(search_term="Enemy", search_method="by_tag")
# 按图层(名称或编号 0~31)
find_gameobjects(search_term="UI", search_method="by_layer")
find_gameobjects(search_term="5", search_method="by_layer")
# 按组件类型
find_gameobjects(search_term="Camera", search_method="by_component")
find_gameobjects(search_term="Rigidbody", search_method="by_component")
# 按层级路径(支持后缀相对路径)
find_gameobjects(search_term="Canvas/Panel/Button", search_method="by_path")
# 按实例 ID
find_gameobjects(search_term="-81840", search_method="by_id")
(语法模板对齐 unity-mcp-skill/references/tools-reference.md)
6.2 包含未激活对象
find_gameobjects(search_term="HiddenTrigger", search_method="by_name",
include_inactive=True)
注意:开启后,by_tag / by_path 会从 Unity 原生 API 退化为手动遍历(见第 3 节),属于正常行为而非缺陷。
6.3 用 batch_execute 批量发现(推荐)
项目 Skill 明确建议用 batch_execute 一次性发起多个 find_gameobjects 搜索,避免逐次往返(SKILL.md):
batch_execute(commands=[
{"tool": "find_gameobjects", "params": {"search_term": "Camera", "search_method": "by_component"}},
{"tool": "find_gameobjects", "params": {"search_term": "Player", "search_method": "by_tag"}},
{"tool": "find_gameobjects", "params": {"search_term": "GameManager", "search_method": "by_name"}}
])
单批默认上限 25 条命令(可在 Unity MCP Tools 窗口调整,最大 100);依赖型操作建议加 fail_fast=True(SKILL.md)。
6.4 典型工作流:搜索 → 读取 → 修改
# 1) 定位
result = find_gameobjects(search_term="Enemy", search_method="by_tag", page_size=50)
ids = result["data"]["instanceIDs"]
# 2) 读取第一个目标的详细信息
detail = read_resource("mcpforunity://scene/gameobject/{0}".format(ids[0]))
# 3) 按需修改(CRUD 走 manage_gameobject)
manage_gameobject(action="delete", instance_id=ids[0])
7. 验证与一致性保障
该工具的契约由服务端集成测试锁定(Server/tests/integration/test_find_gameobjects.py):
test_find_gameobjects_basic_search:验证命令名find_gameobjects与参数searchTerm/searchMethod的正确透传;test_find_gameobjects_by_component:组件搜索参数传递;test_find_gameobjects_pagination_params:字符串型分页参数转为整数;test_find_gameobjects_boolean_coercion:字符串布尔转True;test_find_gameobjects_by_layer/by_path:对应搜索方式透传。
此外,test_tool_signatures_paging.py、test_tool_annotations.py 与 test_cli.py 也覆盖了该工具的分页签名与注解元数据。工具声明为 readOnlyHint=False、destructiveHint=False、idempotentHint=True(find_gameobjects.py)——之所以不是只读,是因为前置的 preflight(refresh_if_dirty=True) 在场景较脏时可能触发资源刷新与域重载,这是使用该工具时需要考虑的轻微副作用(同样见 preflight 调用)。
8. 常见问题与排查要点
| 现象 | 原因与对策 |
|---|---|
by_name 搜不到模糊名称 |
该方式为精确相等匹配;改用 by_tag/by_component 或枚举具体名称 |
| 未激活对象搜不到 | 显式传 include_inactive=True;注意 by_tag、by_path 会切换为手动遍历 |
by_layer 返回空 |
图层名拼写错误或编号越界(合法范围 0~31),可先用编号重试 |
by_component 返回空 |
组件类型名未找到,编辑器会记录 Component type 'xxx' not found 警告;检查完整类型名 |
by_path 在 Prefab 模式下失效 |
已内置 Prefab Stage 兼容处理,如仍异常请确认 search_term 与预制体层级根路径一致 |
| 结果被截断 | 默认每页 50、上限 500,用 nextCursor 翻页或调大 page_size |
9. 参考文件索引
- 工具官方文档:website/docs/reference/tools/core/find_gameobjects.md(由
tools/generate_docs_reference.py自动生成,勿手改examples块) - 服务端实现:Server/src/services/tools/find_gameobjects.py
- 编辑器侧实现:MCPForUnity/Editor/Tools/FindGameObjects.cs
- 搜索核心逻辑:MCPForUnity/Editor/Helpers/GameObjectLookup.cs
- 分页契约:MCPForUnity/Editor/Helpers/Pagination.cs
- 关联资源实现:Server/src/services/resources/gameobject.py
- 集成测试:Server/tests/integration/test_find_gameobjects.py
- 使用模板:unity-mcp-skill/SKILL.md、unity-mcp-skill/references/tools-reference.md、unity-mcp-skill/references/workflows.md