Unity命令行工具

一个用于从命令行控制Unity编辑器的CLI工具,支持Play Mode控制、测试执行、场景操作等功能。

  • by bigdra50
  • Python
  • 本地部署
  • 39 星标
  • 更新于
在 GitHub 查看 bigdra50/unity-mcp-client

使用说明

Unity命令行界面

日本语版

用于从命令行控制Unity编辑器的CLI工具。

概述

从CLI执行Unity编辑器操作:播放模式控制、控制台日志检索、测试执行、场景/GameObject操作等。

# Play Mode control
u play
u stop

# Get console logs (error and above)
u console get -l E

# Execute menu items
u menu exec "Assets/Refresh"

# Execute ContextMenu
u menu context "DoSomething" -t "/Player"

主要特点:

  • 从CLI执行Unity编辑器操作
  • 支持菜单项/上下文菜单执行
  • 同时控制多个Unity实例
  • 域重新加载弹性(自动重新连接)
  • UI Toolkit VisualElement树检查(转储、查询、检查、单击、滚动、文本)
  • 动态API调用(u api call/schema --5243+Unity静态方法)
  • 猴子测试(u uitree monkey)以及结构快照(u uitree snapshot)
  • 使用适当版本打开项目(Unity Hub集成)
  • 项目信息检索(不需要中继服务器)

需求

  • 紫外线 (Python包管理器)
  • Python 3.11+
  • 团结2022.3+
  • Unity Hub(用于 open/editor 命令)

快速开始

1.Unity设置

将UnityBridge包添加到Unity项目中:

# Via OpenUPM (recommended)
openupm add com.bigdra50.unity-bridge

# Or via git URL
# Window > Package Manager > + > Add package from git URL...
# https://github.com/bigdra50/unity-cli.git?path=UnityBridge

2.连接

在Unity编辑器中,打开 Window > Unity Bridge:

  1. 单击启动服务器(启动中继服务器)
  2. 点击连接(Unity→ 继电器连接)

工具栏指示器(右侧)显示连接状态,并允许通过单击进行切换。

3.CLI操作

# Run directly with uvx (no installation required)
uvx --from git+https://github.com/bigdra50/unity-cli u state

# Play Mode control
uvx --from git+https://github.com/bigdra50/unity-cli u play
uvx --from git+https://github.com/bigdra50/unity-cli u stop

# Get console logs (error and above)
uvx --from git+https://github.com/bigdra50/unity-cli u console get -l E

安装

# Global installation
uv tool install git+https://github.com/bigdra50/unity-cli

# With interactive UI (editor selection prompt)
uv tool install "git+https://github.com/bigdra50/unity-cli[interactive]"

# CLI commands (both aliases work the same)
unity-cli state    # Full name
u state            # Short alias

u play
u console get -l E | head -10  # Last 10 error+ logs

# Run Relay Server standalone
unity-relay --port 6500

CLI命令

版本

u version                     # Show CLI version

壳牌完井

# Zsh
u completion -s zsh > ~/.zsh/completions/_unity-cli

# Bash
u completion -s bash >> ~/.bashrc

# Fish
u completion -s fish > ~/.config/fish/completions/unity-cli.fish

# PowerShell
u completion -s powershell >> $PROFILE

打开项目

# Open project with appropriate version (reads ProjectVersion.txt)
u open ./MyUnityProject

# Specify editor version
u open ./MyUnityProject --editor 2022.3.10f1

# Non-interactive mode (for CI/scripts)
u open ./MyUnityProject --non-interactive

# Wait until exit
u open ./MyUnityProject --wait

编辑管理

# List installed editors
u editor list

# Install editor
u editor install 2022.3.10f1

# Install with modules
u editor install 2022.3.10f1 --modules android ios webgl

# Install non-release version with changeset
u editor install 6000.1.0a1 --changeset abc123

项目信息(不需要中继服务器)

# Full project info
u project info ./MyUnityProject

# Unity version only
u project version ./MyUnityProject

# Package list
u project packages ./MyUnityProject
u project packages ./MyUnityProject --include-modules  # Include built-in modules

# Tags & layers
u project tags ./MyUnityProject

# Quality settings
u project quality ./MyUnityProject

# Assembly Definition list
u project assemblies ./MyUnityProject

# JSON output
u --json project info ./MyUnityProject

基本操作(通过中继服务器)

# Check editor state
u state

# Play Mode control
u play
u stop
u pause

# Console logs
u console get                  # All logs (plain text)
u console get --json           # All logs (JSON format)
u console get -s               # All logs with stack traces
u console get -l W             # Warning and above (warning, error, exception)
u console get -l E             # Error and above (error, exception)
u console get -l +W            # Warning only
u console get -l +E+X          # Error and exception only
u console get | head -20       # Last 20 entries
u console get | grep "error"   # Filter by text
u console clear                # Clear console

# Asset refresh
u refresh

# Editor selection
u selection

# Screenshot (capture is default, --burst for burst mode)
u screenshot                           # GameView (default)
u screenshot -s scene                  # SceneView
u screenshot -s camera                 # Camera.Render
u screenshot -p ./output.png           # Custom path
u screenshot --super-size 2            # 2x resolution (game only)
u screenshot -s camera -c "Main Camera" -W 1920 -H 1080
u screenshot --burst -n 10             # Burst: 10 frames
u screenshot --burst -n 5 -f jpg -q 80 # Burst with format/quality

# Pipe-friendly: outputs path only when piped
u screenshot -s game | mcat -i   # Inline display in terminal
u screenshot -s game | pbcopy    # Copy path to clipboard
u screenshot -s game | xargs open  # Open with default viewer

实例管理

# List connected instances
u instances

# Specify target instance
u --instance /Users/dev/MyGame state
u --instance /Users/dev/Demo play

测试执行

# EditMode tests
u tests run edit

# PlayMode tests
u tests run play

# Filtering
u tests run edit --test-names "MyTests.SampleTest"
u tests run edit --group-pattern ".*Integration.*"
u tests run edit --categories "Unit" "Integration"
u tests run edit --assemblies "MyGame.Tests"

# Fire and forget
u tests run edit --no-wait

# List available tests
u tests list edit
u tests list play

# Check running test status
u tests status

场景操作

# Active scene info
u scene active

# Hierarchy
u scene hierarchy                    # Root only (depth 1)
u scene hierarchy --depth 2          # Up to 2 levels
u scene hierarchy --page-size 100    # Custom page size

# Scene operations
u scene load --name MainScene
u scene load --path "Assets/Scenes/Sub.unity" --additive
u scene save
u scene save --path "Assets/Scenes/NewScene.unity"

游戏对象操作

# Find
u gameobject find "Main Camera"
u gameobject find "Player" --iterate-all

# Create
u gameobject create --name "MyCube" --primitive Cube --position 0 1 0

# Modify
u gameobject modify --name "MyCube" --position 5 0 0 --rotation 0 45 0

# Delete
u gameobject delete --name "MyCube"

组件操作

# List components
u component list -t "Main Camera"

# Inspect component
u component inspect -t "Main Camera" -T Camera

# Add component
u component add -t "Player" -T Rigidbody

# Remove component
u component remove -t "Player" -T Rigidbody

菜单/上下文菜单

# Execute menu
u menu exec "Edit/Play"
u menu exec "Assets/Refresh"
u menu exec "Window/General/Console"

# List menus
u menu list                    # All menus
u menu list -f "Assets"        # Filter
u menu list -f "Play" -l 20    # Limit count

# Execute ContextMenu (scene objects)
u menu context "Reset" -t "/Player"

# Execute ContextMenu (ScriptableObject)
u menu context "DoSomething" -t "Assets/Data/Config.asset"

# Execute ContextMenu (Prefab)
u menu context "Initialize" -t "Assets/Prefabs/Enemy.prefab"

资产运营

# Create Prefab
u asset prefab -s "Player" -p "Assets/Prefabs/Player.prefab"

# Create ScriptableObject
u asset scriptable-object -T "GameConfig" -p "Assets/Data/Config.asset"

# Asset info
u asset info "Assets/Data/Config.asset"

UI工具包树检查

检查UI Toolkit VisualElement树并与之交互。使用引用ID进行元素定位。

# List panels / dump tree
u uitree dump
u uitree dump -p "PanelSettings" --json

# Query elements (AND conditions)
u uitree query -p "PanelSettings" -c "action-btn"

# Inspect
u uitree inspect ref_3 --style --children

# Interact
u uitree click -p "PanelSettings" -n "BtnStart"
u uitree text -p "PanelSettings" -n "ScoreLabel"
u uitree scroll -p "PanelSettings" -n "ScrollView" --y 500

# Monkey test (random interactions + error monitoring)
u uitree monkey -p "PanelSettings" -c "action-btn" --count 50 --seed 42

# Structural snapshots (save/diff/list/delete)
u uitree snapshot save -p "PanelSettings" --name baseline
u uitree snapshot diff -p "PanelSettings" --name baseline

动态API调用

通过反射调用任何Unity公共静态方法。5243多种可用方法。

# Search methods
u api schema --type AssetDatabase
u api schema --namespace UnityEditor --limit 20

# Call methods
u api call UnityEngine.Application get_unityVersion
u api call UnityEditor.AssetDatabase Refresh
u api call UnityEditor.EditorApplication ExecuteMenuItem --params '["Window/General/Console"]'

# Offline schema (cached per Unity version)
u api schema --offline --type PlayerSettings

帧录制

# Start recording (camera-based, configurable FPS/format/resolution)
u recorder start --fps 30 -f jpg -q 80
u recorder start --fps 60 -W 1920 -H 1080 -o ./frames

# Stop recording and get results
u recorder stop

# Check recording status
u recorder status

配置

# Show current configuration
u config show

# Generate default .unity-cli.toml
u config init
u config init -o ./custom-config.toml
u config init --force                  # Overwrite existing

选项

常见选项

选项 描述 默认值
--relay-host 中继服务器主机 127.0.0.1
--relay-port 中继服务器端口 6500
--instance, -i 目标Unity实例 默认
--timeout, -t 超时(秒) 10.0
--json, -j 输出JSON格式 false
--quiet, -q 抑制成功消息 false
--verbose 在stderr false上显示请求/响应

测试选项

选项 描述
--test-names, -n 测试名称(完全匹配)
--group-pattern, -g 测试名称的正则表达式模式
--categories, -c NUnit类别
--assemblies, -a 程序集名称
--no-wait 立即返回,无需等待结果

场景层次选项

选项 描述 默认值
--depth, -d 层次深度 1(仅限根)
--page-size 页面大小 50
--cursor 分页光标 0

退出代码

代码 名称 描述
0 SUCCESS 命令已成功完成
1 USAGE_ERROR 参数无效或验证失败
2 TRANSIENT_ERROR 可重试:实例重新加载、繁忙、超时
3 连接错误 中继服务器未运行或无法访问
4 OPERATION_ERROR 命令失败(找不到实例、协议错误等)
5 TEST_FAILURE 测试已运行,但有些失败
u state; echo $?              # 0 = connected, 3 = relay not running
u tests run edit; echo $?     # 0 = all passed, 5 = some failed
u play --quiet 2>/dev/null; echo $?  # Suppress output, check exit code only

环境变量

变量 描述
UNITY_CLI_QUIET 设置为 1 抑制成功消息
UNITY_CLI_VERBOSE 设置为 1 记录对stderr的请求/响应
UNITY_CLI_JSON 设置为 1 默认情况下用于JSON输出
UNITY_CLI_NO_PRETTY 设置为 1 禁用丰富格式
NO_COLOR 设置为禁用颜色(标准)

AI代理技能

AI编码代理(Claude Code、Codex、Gemini CLI、Cursor、GitHub Copilot、Windsurf等)的工作流技能。符合 agentskills.io 网站 规格。

选项1:GitHub CLI(推荐,gh 2.90.0+)

# Interactive: pick skills from a list
gh skill install bigdra50/unity-cli

# Install a single skill
gh skill install bigdra50/unity-cli unity-verify

# Install all skills at once (Claude Code, user scope)
for s in unity-shared unity-verify unity-debug unity-build \
         unity-scene unity-asset unity-perf unity-ui unity-api; do
  gh skill install bigdra50/unity-cli "$s" --agent claude-code --scope user
done

# Pin to a specific release
gh skill install bigdra50/unity-cli unity-verify --pin v3.11.0

通过以下方式支持40多个代理 --agent (claude代码、github副本、游标、codex、gemini cli等)。默认范围为 project;使用 --scope user 用于全局安装。

选项2:技能CLI(跨代理,无需gh)

# Install all skills (project-local)
npx skills add github:bigdra50/unity-cli

# Install globally (user-level)
npx skills add github:bigdra50/unity-cli -g

# Install specific skills only
npx skills add github:bigdra50/unity-cli -s unity-ui unity-api

看 技能CLI 了解详情。

选项3:手动(git clone)

git clone https://github.com/bigdra50/unity-cli.git

# Single skill
cp -r unity-cli/skills/unity-verify ~/.claude/skills/

# All skills
cp -r unity-cli/skills/* ~/.claude/skills/

技能

技能 描述
unity-verify 编译和测试验证(刷新→ 错误检查)
unity-debug 错误调查
unity-build 建立管道
unity-scene 场景构建
unity-asset 资产和依赖关系管理
unity-perf 分析器分析
unity-ui UI测试(uitree+monkey+快照→ 播放模式)
unity-api 动态API调用(5243+方法)
unity-shared 通用规则(由其他技能自动加载)

食谱

看 docs/recipes.md 用于管道、脚本和工具组合示例。

u screenshot -s game | mcat -i         # Inline display in terminal
u console get -l E | head -10                  # Last 10 errors
u instances --json | jq -r '.[].instance_id'   # Extract paths

建筑

flowchart TB
    subgraph CLI["u (Python)"]
        direction TB
        RC[RelayConnection: TCP communication]
        EB[Exponential Backoff: 500ms → 8s]
        RID[request_id: idempotency guarantee]
    end

    subgraph Relay["Relay Server (Python)"]
        direction TB
        IR[InstanceRegistry: multiple Unity management]
        Cache[RequestCache: idempotency cache]
        HB[Heartbeat: Single Outstanding PING]
        Q[Queue: FIFO max 10]
    end

    subgraph Unity["UnityBridge (C#)"]
        direction TB
        Client[RelayClient: connection management]
        Dispatcher[CommandDispatcher: BridgeTool attribute]
        Reload[BridgeReloadHandler: reconnection]
    end

    CLI -->|TCP:6500| Relay
    Relay -->|TCP:6500| Unity

协议规范

看 docs/protocol-spec.md 了解详情。

  • 成帧:4字节大端长度+JSON
  • 状态机:已断开连接→ 准备就绪→ BUSY → 给重新装入
  • 心跳:间隔5秒,超时15秒(3次重试)
  • 重试:指数回退(500ms→ 8s、 最大30秒)

故障排除

# Check if Relay Server is running
lsof -i :6500            # macOS / Linux
netstat -ano | findstr :6500   # Windows

# Check connected instances
u instances

# Check Unity console for errors
u console get -l E

v2.x → v3.0迁移

更改 v2.x v3.0
命令名称 unity-mcp unity-cli
连接目标 Unity直接(6400) 中继服务器(6500)
协议 8字节成帧 4字节成帧
多个实例 不支持 支持
# v2.x
unity-mcp --port 6400 state

# v3.0
u state  # Via Relay
u --instance /path/to/project state  # Specific instance

许可证

MIT许可证