> For the complete documentation index, see [llms.txt](https://developers-apps-in-toss.toss.im/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developers-apps-in-toss.toss.im/documentation/api-and-sdk-zh/unity/integration.md).

# 接入

App in Toss 小程序 **基于网页**运行。要将 Unity 游戏制作成小程序，需要将项目 **构建为 WebGL**。通过 WebGL 构建，Unity 游戏会转换为可在浏览器中运行的形式，并可在 App in Toss 环境中作为小程序提供。

仅为 Unity 提供的 **App in Toss Unity 包**安装后，无需配置 Vite 项目或实现 JS Bridge，即可从 WebGL 构建到小程序打包一次性处理。

***

### 使用 App in Toss Unity SDK 的原因

使用 App in Toss Unity 包可获得以下优势。

* **较短的迁移周期**：用 Unity 开发的游戏无需单独配置 Vite 项目或实现 JS Bridge，即可轻松快速地迁移为 App in Toss 小程序。
* **更高的稳定性和用户体验**：将加载时间缩短到 1/5 左右，提升小程序稳定性，并为用户提供更好的体验。
* **查看更多性能指标**：可查看崩溃率、加载时间、FPS 等更多游戏性能指标。
* **默认提供的加载画面**：加载画面已默认包含在 SDK 中，因此合作方无需单独配置加载画面。

{% hint style="info" %}
实际应用案例某款游戏在使用手动迁移方式时，加载时间约为 20 秒，导致大量用户流失，CS 咨询也暴增。

切换为 Unity SDK 后，加载时间 **1 秒**，从而大幅改善了这些问题。
{% endhint %}

***

### 什么是 SDK 集成？

SDK 集成是指在 Unity 中自动处理 App in Toss 集成所需流程的方式。

* 用于 WebView SDK 集成的 **JS Bridge**已默认包含。
* 在 Unity 中 **通过 C# 代码直接调用 App in Toss API**。
* 从 WebGL 构建到 `.ait` 文件生成都可一次性自动化完成。
* 崩溃率、加载时间、FPS 等游戏性能指标会自动收集。

如果用 Unity 开发小程序，建议以 App in Toss 提供的 Unity SDK 为准进行开发。

{% hint style="info" %}
**手动集成**

如果不使用 App in Toss Unity 包而需要自行配置 WebGL 构建或实现 JS Bridge， [手动集成指南](/documentation/api-and-sdk-zh/unity/manual-integration.md)。
{% endhint %}

***

### 安装 SDK

#### 方法 1：Package Manager（推荐）

1. 在 Unity Editor 中 `Window` > `Package Manager`。
2. 左上角 `+` 按钮， `Add package from git URL...`。
3. 输入 Git URL 后 **Install**进行安装。

```
https://github.com/toss/apps-in-toss-unity-sdk.git
```

{% hint style="info" %}
**版本固定**

若要固定到特定版本， `#release/v2.4.5`等发布标签。发布列表请参考 [GitHub Releases](https://github.com/toss/apps-in-toss-unity-sdk/releases)可在此处查看。
{% endhint %}

#### 方法 2：直接修改 manifest.json

项目的 `Packages/manifest.json` 文件中也可以直接添加：

```json
{
  "dependencies": {
    "im.toss.apps-in-toss-unity-sdk": "https://github.com/toss/apps-in-toss-unity-sdk.git#release/v2.4.5"
  }
}
```

#### 支持的 Unity 版本

* **最低版本**：Unity 2021.3
* **推荐版本**：Unity 6 及以上
* 支持 Unity 2021.3 及之后的所有版本。

#### 确认安装完成

如果安装正常完成：

* Package Manager 列表中会显示 **AppsInToss SDK**。
* Unity 菜单顶部会新增 **AIT** 项目。
* `Packages/Apps In Toss SDK/Runtime/SDK` 路径下会生成 `AIT.*.cs` 文件。

***

### 包组件

App in Toss Unity 包为了让你在 WebGL 环境中使用 App in Toss SDK， **C# API 层**和 **JavaScript Bridge(.jslib)** 这两部分一起提供。

#### C# API Wrapper

这是提供给 Unity C# 代码直接调用 App in Toss 功能的 API。

* 可将 App in Toss API 封装为 C# 方法，方便使用。
* 内部通过 `DllImport("__Internal")`在 WebGL 构建时与 JS 函数连接。
* 无需额外 JavaScript，仅靠 C# 代码就能集成 App in Toss。

#### JavaScript Bridge (.jslib)

`.jslib` 文件在 Unity WebGL 环境中起到连接 C# 与 JavaScript 的桥梁作用。

* C# 中调用的 JS 函数都定义在这个文件里。
* 实际与 App in Toss WebView SDK 通信的逻辑也在这里处理。
* 也支持 JS → C# 调用，因此可以构建双向消息通信结构。

***

### AIT 菜单

安装 App in Toss Unity 包后，Unity Editor 顶部会新增 **AIT** 菜单。通过这个菜单，可使用 WebGL 构建、打包、启动测试服务器等集成过程中所需的大多数功能。

| 菜单                    | 说明                                                     |
| --------------------- | ------------------------------------------------------ |
| **Dev Server**        | 运行开发测试服务器。启用 Mock Bridge，可在本地浏览器中测试。                   |
| **Production Server** | 以生产配置运行本地服务器。可进行与实际发布环境相似的测试。                          |
| **Build & Package**   | WebGL 构建 + `.ait` 打包一次完成。是最常使用的选项。                     |
| **Publish**           | `.ait` 将文件上传到 App in Toss 控制台。Configuration 中需要注册发布密钥。 |
| **Clean**             | 删除之前的构建产物。                                             |
| **Open Build Output** | 直接打开保存构建产物的文件夹。                                        |
| **Configuration**     | 设置与 App in Toss 小程序集成相关的构建选项。                          |
| **Debug**             | 可以查看日志或检查内部状态。                                         |

***

### 设置

安装 SDK 后，在 Unity Editor 菜单中 `AIT` > `Configuration`点击它打开设置面板。

#### 必需设置

| 设置           | 说明                                  |
| ------------ | ----------------------------------- |
| **应用 ID**    | 与在 App in Toss 控制台注册的 `appName`必须相同 |
| **应用图标 URL** | 将显示为小程序图标的图片 URL（必填）                |
| **显示名称**     | 加载画面中显示的应用名称                        |
| **主色调**      | 品牌色（用于进度条等）                         |

{% hint style="info" %}

* **应用 ID**需与在 App in Toss 控制台注册的 `appName`必须相同。
* **图标**在测试阶段可以不填，但正式发布时必须注册。
* 服务器设置中的 Granite、Vite 相关项用于沙盒应用测试。
  {% endhint %}

各构建选项的详细设置请参考构建配置文件文档。

***

### 第一次构建

#### 1. 确认设置

1. `AIT` > `Configuration` 在菜单中确认设置。
2. **应用图标 URL**请确认已填写（必填）。

#### 2. 运行开发服务器

开发阶段使用 Dev Server 模式：

1. `AIT` > `Dev Server` > `Start Server` 菜单。
2. Unity WebGL 构建将自动运行。
3. 构建完成后会启动本地开发服务器。
4. 会自动在浏览器中打开，或者访问控制台中显示的 URL。

#### 3. 生产构建

若要生成发布用构建：

1. `AIT` > `Build & Package` 菜单。
2. 构建完成后 `ait-build/dist/` 可在文件夹中查看产物。

#### 4. 发布

若要部署到 Apps in Toss 平台：

1. `AIT` > `Publish` 菜单。
2. 必须设置发布密钥（在 Configuration 中设置）。

***

### 使用 SDK

安装 App in Toss Unity SDK 后，可直接在 C# 代码中 `AIT.*` 调用 API。无需手写 JS Bridge，仅通过 Unity 代码即可使用 App in Toss 功能。

App in Toss API 大多以异步（async）方式运行：

```csharp
var result = await AIT.SomeApi(options);
```

* 成功时会返回对应 API 的结果模型。
* 失败时 `继承自 AITException`可能会发生异常，因此需要进行异常处理。

可在 App in Toss SDK 参考文档中查看完整可用的 AIT API 列表。WebView SDK 的 `getDeviceId`在 Unity SDK 中 `AIT.GetDeviceId()`以类似 PascalCase 的形式调用。

详细使用模式请参考 API 使用模式文档。

**示例**

```csharp
using AppsInToss;
using UnityEngine;
using System.Threading.Tasks;

public class GameManager : MonoBehaviour
{
    async void Start()
    {
        try
        {
            // 查询设备 ID
            string deviceId = await AIT.GetDeviceId();
            Debug.Log($"Device ID: {deviceId}");

            // 查询平台 OS
            PlatformOS os = await AIT.GetPlatformOS();
            Debug.Log($"平台：{os}");

            // 检查网络状态
            NetworkStatus status = await AIT.GetNetworkStatus();
            Debug.Log($"网络：{status}");
        }
        catch (AITException ex)
        {
            Debug.LogError($"API 调用失败：{ex.Message}（代码：{ex.Code}）");
        }
    }

    // 触觉反馈示例
    public async void VibrateDevice()
    {
        try
        {
            var options = new GenerateHapticFeedbackOptions {
                style = "medium"
            };

            await AIT.GenerateHapticFeedback(options);
            Debug.Log("已生成触觉反馈");
        }
        catch (AITException ex)
        {
            Debug.LogError($"触觉反馈失败：{ex.Message}");
        }
    }
}
```

{% hint style="info" %}
**查看示例代码**

以下文件是用于 E2E 测试的示例代码，可查看如何实际使用应用内广告/应用内支付。

* [应用内广告示例](https://github.com/toss/apps-in-toss-unity-sdk/blob/main/Tests~/E2E/SharedScripts/Runtime/AdV2Tester.cs)
* [应用内支付示例](https://github.com/toss/apps-in-toss-unity-sdk/blob/main/Tests~/E2E/SharedScripts/Runtime/IAPv2Tester.cs)
  {% endhint %}

***

### 测试

App in Toss AIT API **在普通浏览器环境中无法运行。** 仅能在 App in Toss 运行环境中使用该功能。

可测试的环境有两种：

#### 1. 在沙盒应用中测试

这是用于开发中功能验证的测试应用。可运行 Unity WebGL 构建并确认 AIT API 是否正常连接。

* 下载沙盒应用

#### 2. 上传 .ait 文件后测试

1. 在 AIT 菜单中 `Build & Package`做 `.ait` 生成文件。
2. [App in Toss 控制台](https://apps-in-toss.toss.im/)上传到其中。
3. 通过二维码运行小程序。

详细方法请参考《在 Toss App 中测试》文档。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://developers-apps-in-toss.toss.im/documentation/api-and-sdk-zh/unity/integration.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
