# Unity SDK 基础集成指南

本指南将引导您将 Pushwoosh Unity SDK 集成到您的应用程序中。

## 先决条件

<Aside type="note" title="要求">
 - 一个 [Pushwoosh 账户](https://sso.pushwoosh.com/login)。
 - 在您的账户中设置好的一个 [Pushwoosh 项目](/zh/product/first-steps/start-with-your-project/create-your-project)。
 - Unity 2021.3 或更高版本。
 - **对于 iOS：**
    - 一个配置为发送推送通知的 iOS 平台。我们建议使用[基于令牌的身份验证](/zh/developer/first-steps/connect-messaging-services/ios-configuration/ios-token-based-configuration/)作为最简单的方法。
    - 将网关设置为 `Sandbox` 以向模拟器发送推送。
 - **对于 Android：**
    - 一个[已配置的 Android 平台](/zh/developer/first-steps/connect-messaging-services/android-configuration/android-firebase-configuration)。
    - 来自您 Firebase 项目的 `project number`（也称为发送者 ID）、`google-services.json` 文件和 `package name`。
    - 一个连接到您 Android 应用程序的 Firebase 项目。如果需要，请遵循 [Firebase 设置指南](https://firebase.google.com/docs/android/setup#manually_add_firebase)。
 - 您的 `Pushwoosh Application Code` 和来自 Pushwoosh 控制面板的 [Pushwoosh Device API Token](/zh/developer/api-reference/api-access-token/#device-api-token)。
</Aside>

## 集成步骤

### 1. 添加 Pushwoosh Unity SDK

<Tabs>
  <TabItem label="通过 Scoped Registry 使用 UPM (推荐)">

将以下内容添加到您的 `Packages/manifest.json` 中：

```json title="Packages/manifest.json"
{
  "dependencies": {
    "com.pushwoosh.unity.core": "6.2.7",
    "com.pushwoosh.unity.android": "6.2.7",
    "com.pushwoosh.unity.ios": "6.2.7"
  },
  "scopedRegistries": [
    {
      "name": "npmjs",
      "url": "https://registry.npmjs.org",
      "scopes": ["com.pushwoosh"]
    }
  ]
}
```

仅添加您需要的平台包。例如，如果您只针对 iOS，请省略 `com.pushwoosh.unity.android`。

  </TabItem>
  <TabItem label="通过 Git URL 使用 UPM">

在 Unity 中，转到 **Window > Package Manager > + > Add package from git URL** 并逐一添加以下 URL：

```
https://github.com/Pushwoosh/pushwoosh-unity.git?path=com.pushwoosh.unity.core
https://github.com/Pushwoosh/pushwoosh-unity.git?path=com.pushwoosh.unity.android
https://github.com/Pushwoosh/pushwoosh-unity.git?path=com.pushwoosh.unity.ios
```

  </TabItem>
  <TabItem label=".unitypackage">

从 [GitHub Releases](https://github.com/Pushwoosh/pushwoosh-unity/releases) 下载 `Pushwoosh.unitypackage` 并通过 **Assets > Import Package > Custom Package** 导入。

  </TabItem>
</Tabs>

### 2. 安装外部依赖管理器

该 SDK 需要 [External Dependency Manager for Unity (EDM4U)](https://github.com/googlesamples/unity-jar-resolver) 来解析原生的 Android 和 iOS 依赖项。

将以下作用域注册表添加到您的 `Packages/manifest.json` 中：

```json
{
  "scopedRegistries": [
    {
      "name": "package.openupm.com",
      "url": "https://package.openupm.com",
      "scopes": ["com.google.external-dependency-manager"]
    }
  ]
}
```

然后将该包添加到您的依赖项中：

```json
"com.google.external-dependency-manager": "1.2.183"
```

### 3. 初始化 SDK

创建一个 `PushNotificator.cs` 脚本并将其附加到场景中的任何 GameObject 上：

```csharp title="PushNotificator.cs"
using UnityEngine;
using System.Collections.Generic;

public class PushNotificator : MonoBehaviour
{
    void Start()
    {
        Pushwoosh.ApplicationCode = "XXXXX-XXXXX";
        Pushwoosh.FcmProjectNumber = "XXXXXXXXXXXX";

        Pushwoosh.Instance.OnRegisteredForPushNotifications += (token) => {
            Debug.Log("Push token: " + token);
        };

        Pushwoosh.Instance.OnFailedToRegisteredForPushNotifications += (error) => {
            Debug.Log("Registration failed: " + error);
        };

        Pushwoosh.Instance.RegisterForPushNotifications();
    }
}
```

替换：
- `XXXXX-XXXXX` 为您的 Pushwoosh Application Code。
- `XXXXXXXXXXXX` 为您的 Firebase 项目编号 (仅限 Android)。

### 4. iOS 原生设置

#### 4.1 功能 (Capabilities)

从 Unity 构建 iOS 项目后，打开生成的 Xcode 项目并在 **Signing & Capabilities** 中添加以下功能：

- **推送通知 (Push Notifications)**
- **后台模式 (Background Modes)** 并勾选 **远程通知 (Remote notifications)**

对于时间敏感通知 (iOS 15+)，还需添加 **时间敏感通知 (Time Sensitive Notifications)** 功能。

#### 4.2 Info.plist

将 [Pushwoosh Device API Token](/zh/developer/api-reference/api-access-token/#device-api-token) 添加到您的 `Info.plist` 中：

```xml title="Info.plist"
<key>Pushwoosh_API_TOKEN</key>
<string>__PUSHWOOSH_DEVICE_API_TOKEN__</string>
```

#### 4.3 消息送达跟踪

向您的 Xcode 项目添加一个通知服务扩展 (Notification Service Extension) 目标。这对于在 iOS 上实现准确的送达跟踪和富媒体是必需的。

请遵循[原生指南](/zh/developer/pushwoosh-sdk/ios-sdk/setting-up-pushwoosh-ios-sdk/basic-integration-guide/#4-message-delivery-tracking)来添加扩展目标。

### 5. Android 原生设置

#### 5.1 添加 Firebase 配置文件

将 `google-services.json` 文件放入您的 Unity 项目的 **Assets** 目录中。

#### 5.2 添加 Pushwoosh 元数据

将 [Pushwoosh Device API Token](/zh/developer/api-reference/api-access-token/#device-api-token) 添加到您的 `Assets/Plugins/Android/AndroidManifest.xml` 文件的 `<application>` 标签内：

```xml title="AndroidManifest.xml"
<meta-data android:name="com.pushwoosh.apitoken" android:value="__YOUR_DEVICE_API_TOKEN__" />
```

<Aside type="caution">
请确保在您的 Pushwoosh 控制面板中为该令牌授予对正确应用的访问权限。[了解更多](/zh/developer/api-reference/api-access-token/#edit-token)
</Aside>

### 6. 运行项目

1. 在您的目标平台上构建并运行项目。
2. 在出现提示时，授予推送通知权限。
3. 前往 Pushwoosh 控制面板并[发送一条推送通知](/zh/product/messaging-channels/push-notifications/send-push-notifications/one-time-push)。

## 扩展集成

至此，您已经可以发送和接收推送通知了。以下部分将介绍 SDK 的核心功能。

### 推送通知事件监听器

SDK 提供了两个用于处理推送通知的事件监听器：

- `OnPushNotificationsReceived` — 当推送通知到达时触发
- `OnPushNotificationsOpened` — 当用户点击通知时触发

在 SDK 初始化期间设置这些监听器：

```csharp title="PushNotificator.cs"
void Start()
{
    Pushwoosh.ApplicationCode = "XXXXX-XXXXX";
    Pushwoosh.FcmProjectNumber = "XXXXXXXXXXXX";

    Pushwoosh.Instance.OnPushNotificationsReceived += (payload) => {
        Debug.Log("Push received: " + payload);
    };

    Pushwoosh.Instance.OnPushNotificationsOpened += (payload) => {
        Debug.Log("Push opened: " + payload);
    };

    Pushwoosh.Instance.RegisterForPushNotifications();
}
```

### 用户配置

通过识别用户并设置其属性来个性化推送通知：

```csharp
// 设置用户 ID 以进行跨设备跟踪
Pushwoosh.Instance.SetUserId("user-123");

// 设置用户邮箱
Pushwoosh.Instance.SetEmail("user@example.com");

// 同时设置用户 ID 和邮箱
Pushwoosh.Instance.SetUser("user-123", new List<string> { "user@example.com" });

// 设置首选语言
Pushwoosh.Instance.SetLanguage("en");
```

### 标签 (Tags)

标签是分配给设备的键值对，可用于用户分群和定向消息发送：

```csharp
// 字符串标签
Pushwoosh.Instance.SetStringTag("favorite_category", "electronics");

// 整数标签
Pushwoosh.Instance.SetIntTag("purchase_count", 5);

// 列表标签
Pushwoosh.Instance.SetListTag("interests", new List<object> { "sports", "music", "tech" });

// 获取所有标签
Pushwoosh.Instance.GetTags((tags, error) => {
    if (error != null) {
        Debug.Log("Error: " + error.Message);
        return;
    }
    foreach (var tag in tags) {
        Debug.Log(tag.Key + ": " + tag.Value);
    }
});
```

### 事件 (Events)

跟踪用户行为以分析行为并触发自动化消息：

```csharp
// 跟踪登录事件
Pushwoosh.Instance.PostEvent("login", new Dictionary<string, object> {
    { "username", "user-123" },
    { "login_type", "email" }
});

// 跟踪购买事件
Pushwoosh.Instance.PostEvent("purchase", new Dictionary<string, object> {
    { "product_id", "SKU-001" },
    { "price", 29.99 },
    { "currency", "USD" }
});
```

### 通信偏好设置

允许用户通过编程方式选择接收或退订推送通知：

```csharp
// 启用通信
Pushwoosh.Instance.SetCommunicationEnabled(true);

// 禁用通信
Pushwoosh.Instance.SetCommunicationEnabled(false);

// 检查当前状态
bool isEnabled = Pushwoosh.Instance.IsCommunicationEnabled();
```

### 角标管理

在支持的平台上控制应用角标数量：

```csharp
// 将角标设置为特定数字
Pushwoosh.Instance.SetBadgeNumber(3);

// 增加角标
Pushwoosh.Instance.AddBadgeNumber(1);

// 清除角标
Pushwoosh.Instance.SetBadgeNumber(0);
```

## 问题排查

如果您在集成过程中遇到任何问题，请参考[支持和社区](/zh/developer/pushwoosh-sdk/support-and-community)部分。