UnityMCP

UnityMCP

🚀 Unity MCP 入门指南

本指南将帮助你快速集成和使用 MCP 协议到你的 Unity 项目中,详细介绍安装配置、使用示例、通信协议等内容。

🚀 快速开始

按照以下步骤,你可以轻松地在 Unity 项目中集成和使用 MCP 协议。

📦 安装指南

Unity 端安装步骤

  1. 下载最新版本的 MCP 模块。
  2. 将模块文件(.unitypackage)导入到你的 Unity 项目中。
  3. Assets/Editor 文件夹下创建一个新的空文件,命名为 McpServerSettings.cs
  4. 添加以下内容到该文件:
using UnityEngine;
using ModelContextProtocol;

public static class McpServerSettings {
public const bool StartOnLaunch = true; // 是否在Unity启动时自动启动服务器
public const bool RestartOnPlayModeChange = true; // 在切换Play模式时是否重启服务器
}
  1. 打开 Edit > Preferences > Projects > External Tools,勾选 Enable MCP Server Support

TypeScript 端安装步骤

  1. 克隆 MCP 示例项目仓库。
  2. 安装依赖项:
npm install @model-context-protocol/mcp-typings @model-context-protocol/mcp-server
  1. 启动 TypeScript 服务器:
npm run start

💻 使用示例

基本 Command Handler(C#)

Assets/Editor 文件夹下创建一个新的 C# 脚本,命名为 HelloWorldCommandHandler.cs

using UnityEngine;
using ModelContextProtocol;

public class HelloWorldCommandHandler : CommandHandler {
protected override void Handle(string[] args) {
// 在此处实现你的业务逻辑
Debug.Log("Hello, World!");
}
}

基本 Resource Handler(C#)

Assets/Editor 文件夹下创建一个新的 C# 脚本,命名为 MyResourceHandler.cs

using UnityEngine;
using ModelContextProtocol;

public class MyResourceHandler : ResourceHandler {
protected override async Task Handle(Request request) {
// 在此处实现你的业务逻辑
return await Response.Ok("Hello, World!");
}
}

基本 Command Handler(TypeScript)

handlers/commands 文件夹下创建一个新的 TypeScript 文件,命名为 hello-world.ts

import { CommandHandler } from "@model-context-protocol/mcp-server";

export class HelloWorldCommand extends CommandHandler {
async execute(args: string[]): Promise<string> {
// 在此处实现你的业务逻辑
return "Hello, World!";
}
}

🔧 技术细节

通信协议

基本请求响应结构(JSON)

{
"id": "123",         # 请求唯一标识符
"type": "command",   # 请求类型,可以是 command、resource 或者 prompt
"method": "GET",     # HTTP 方法,如 GET, POST 等
"path": "/hello",    # 请求路径
"body": {           # 请求正文
"message": "Hello"
}
}

响应结构(JSON)

{
"id": "123",
"success": true,     # 是否成功
"result": {         # 响应结果
"greeting": "World"
}
}

请求流程

  1. 客户端发送请求到 TypeScript 服务器。
  2. 服务器将请求转发到 Unity MCP Server。
  3. Unity 根据请求路径找到对应的 Handler。
  4. Handler 在 Unity 主线程处理请求。
  5. 响应结果返回给 TypeScript 服务器。
  6. 服务器将结果格式化为 JSON 返回给客户端。

配置参考

示例 McpServerSettings.cs

using UnityEngine;
using ModelContextProtocol;

public static class McpServerSettings {
public const bool StartOnLaunch = true; // 是否在Unity启动时自动启动服务器
public const bool RestartOnPlayModeChange = true; // 在切换Play模式时是否重启服务器
}

示例 mcp-config.json

{
"port": 5005,         # MCP Server 监听端口
"workers": 4,        # 工作进程数
"logging": {
"level": "debug",   # 日志级别:debug、info、warning、error
"console": true      # 是否启用控制台日志
}
}

📚 详细文档

故障排除

问题描述 解决方案
MCP Server 没有启动 确保 Unity 启动时自动启动服务器功能已启用
请求无响应 检查防火墙设置,确保端口开放
500 错误 检查日志文件以获取更多错误信息

更多资源

  • 0 关注
  • 0 收藏,31 浏览
  • system 提出于 2025-10-07 03:03

相似服务问题

相关AI产品