文档

初始化服务以处理启动顺序

初始化 Unity Gaming Services、Authentication 和应用内购(IAP),以便您可以与直接面向消费者的(D2C)支付提供商集成。
阅读时间3 分钟最后更新于 3 个月前

创建一个脚本来初始化 Unity Gaming Services (UGS) 以处理 IAP 的启动顺序。此启动脚本可以执行以下操作:
  1. 初始化 Unity Gaming Services。
  2. 设置 Authentication 事件处理程序。
  3. 登录。
  4. 初始化 IAP 并获取 Remote Catalog。有关更多信息,请参阅获取远程目录。
注意
在初始化 UGS 之前设置您的环境。
在初始化脚本中,确保在 Inspector 中分配
PurchaseManager
组件。
PurchaseManager
组件是在下一步获取 Remote Catalog 步骤中创建的。

初始化服务示例脚本

以下示例脚本名为
ServiceOrchestrator
:
重要
建议的最佳做法是不要使用匿名登录作为身份验证方法,因为在会话令牌丢失后,这种做法不会持续购买。如果无摩擦 特定于平台的提供程序 (/authentication/ approaches-to-authentication#platform-specific-authentication)不适用于您的应用程序,请参阅 匿名身份验证和链接 (/authentication/anonymous-auth-and-linking)。
using System;using System.Threading.Tasks;using Unity.Services.Authentication;using Unity.Services.Core;using UnityEngine;// Ensure you have reference to your PurchaseManager namespace if applicablepublic class ServiceOrchestrator :MonoBehaviour{ // Assign this in the Inspector public PurchaseManager purchaseManager; async void Awake() { try { { // 1.初始化 Unity Gaming Services await Unity.Services.Core.UnityServices.InitializeAsync(); // 2.设置身份验证事件处理程序 SetupEvents(); // 3.登录 await SignUpAnonymouslyAsync(); // 4.初始化 IAP 和获取目录 await purchaseManager.InitializeIAP(); } catch(异常 e) { Debug.LogException(e); } } // Setup authentication event handlers if desired void SetupEvents() { AuthenticationService.Instance.SignedIn += () => { // Shows how to get a playerID Debug.Log($"PlayerID: {AuthenticationService.Instance.PlayerId}"); // Shows how to get an access token Debug.Log($"Access Token: {AuthenticationService.Instance.AccessToken}"); }; AuthenticationService.Instance.SignInFailed += (err) => { Debug.LogError(err); }; AuthenticationService.Instance.SignedOut += () => { Debug.Log("Player signed out."); }; AuthenticationService.Instance.Expired += () => { Debug.Log("Player session could not be refreshed and expired."); }; } // Sign in async Task SignUpAnonymouslyAsync() { try { { await AuthenticationService.Instance.SignInAnonymouslyAsync(); Debug.Log("Sign in anonymously succeeded!"); Debug.Log($"PlayerID: {AuthenticationService.Instance.PlayerId}"); } catch(AuthenticationException ex) { // Compare error code to AuthenticationErrorCodes Debug.LogException(ex); } catch (RequestFailedException ex) { // Compare error code to CommonErrorCodes Debug.LogException(ex); } }}

后续步骤

本页面是使用 IAP 设置 D2C 支付提供商的工作流程的一部分。要继续此工作流程,请选择以下选项之一: