主题
Unity 从零接入晞晗IM
本页演示在 Unity 2022.3 LTS 项目中启动 XHIM、登录账号并发送文字消息。
1. 准备信息
开始前请准备:
- App ID;
- Server URL;
- 当前账号的 User ID 和短期 Access Token;
- 与目标平台匹配的 XHIM native plugin;
- 服务端提供的 Endpoint Signing Key ID 和公钥。
Access Token 应由游戏业务后台签发,不要写进 Scene、Prefab 或 PlayerPrefs。
2. 安装 UPM 包
在 Unity Package Manager 中选择 Add package from disk,然后选择本包的 package.json。
把对应平台的 xhim_core_v1 放入 Unity 的 Assets/Plugins,并在 Inspector 中只启用正确的系统和 CPU:
- Windows:x86_64;
- macOS:arm64 / x86_64;
- iOS:arm64;
- Android:arm64-v8a / x86_64。
3. 创建客户端
建议在账号级 Service 中保存客户端,不要挂在会频繁销毁的页面 GameObject 上。
csharp
using XihanSoftware.XHIM;
var client = new XHIMUnityClient(new XHIMUnityConfiguration
{
AppId = "your-app-id",
StoragePath = accountDatabasePath,
BootstrapUrl = "https://im.example.com",
EndpointSigningKeyId = endpointKeyId,
EndpointSigningPublicKeyBase64 = endpointPublicKey
});4. 启动并登录
csharp
await client.StartAsync();
await client.LoginAsync(currentUserId, accessToken);只有登录成功后再加载会话和发送消息。Token 更新后调用:
csharp
await client.UpdateCredentialAsync(newAccessToken);5. 发送第一条消息
conversationId 来自你查询或创建的会话:
csharp
await client.SendTextAsync(
conversationId,
"你好,XHIM",
Guid.NewGuid().ToString("N")
);6. 网络恢复与退出
网络从不可用恢复时通知 SDK:
csharp
client.NotifyNetworkAvailable();退出账号:
csharp
await client.LogoutAsync();
client.Dispose();如果需要更新 Unity UI,请把结果切回 Unity 主线程后再刷新 GameObject。
7. 常见问题
- Editor 可以运行,打包后找不到库:检查 native plugin 的平台和 CPU 选择;
- 登录失败:确认 Token 属于当前 App ID 和 User ID;
- IL2CPP 构建后方法丢失:检查 linker 配置是否保留 XHIM 包和 native 入口;
- 切换账号后出现旧数据:每个账号使用独立
StoragePath,并先销毁旧客户端。
需要修改场景组织、页面状态或消息渲染时,再阅读客户端二次开发指南。