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

> 初始化 Unity Gaming Services、Authentication 和应用内购(IAP)，以便您可以与直接面向消费者的(D2C)支付提供商集成。

创建一个脚本来初始化 Unity Gaming Services (UGS) 以处理 IAP 的启动顺序。此启动脚本可以执行以下操作：

1. 初始化 Unity Gaming Services。
2. 设置 Authentication 事件处理程序。
3. 登录。
4. 初始化 IAP 并获取 Remote Catalog。有关更多信息，请参阅[获取远程目录](./fetch-remote-catalog.md)。

> **Note:**
>
> 在初始化 UGS 之前[设置您的环境](workflow#configure-your-environment-in-the-unity-editor)。

在初始化脚本中，确保在 Inspector 中分配 `PurchaseManager` 组件。`PurchaseManager` 组件是在下一[步获取 Remote Catalog](./fetch-remote-catalog.md) 步骤中创建的。

## 初始化服务示例脚本##initialize-services-example-script

以下示例脚本名为 `ServiceOrchestrator`：

> **Important:**
>
> 建议的最佳做法是不要使用匿名登录作为身份验证方法，因为在会话令牌丢失后，这种做法不会持续购买。如果无摩擦 特定于平台的提供程序 (/authentication/ approaches-to-authentication#platform-specific-authentication)不适用于您的应用程序，请参阅 匿名身份验证和链接 (/authentication/anonymous-auth-and-linking)。

```csharp
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 applicable

public 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);
        }
    }
}
```

## 后续步骤##next-steps

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

[Integrate D2C payment providers](./workflow.md#initialize-services-to-handle-the-start-up-sequence): 返回到 Integration D2C payment providers with IAP workflow（将 D2C 支付提供商与 IAP 工作流程集成）页面。
[Fetch your Remote Catalog](./fetch-remote-catalog.md): 继续工作流程中的下一步以设置 D2C 支付提供商。
