# 起動シーケンスをハンドルするサービスの初期化

> Unity Gaming Services、Authentication、アプリ内課金(IAP)を初期化して、Direct to Consumer (D2C)の支払いプロバイダーと統合できるようにします。

IAP の起動シーケンスをハンドルするために Unity Gaming Services（UGS）を初期化するスクリプトを作成します。このスタートアップスクリプトは、以下の行うことができます。

1. Unity Gaming Services を初期化します。
2. Authenticationイベント ハンドラーを設定します。
3. サインインします。
4. IAP を初期化し、リモートカタログをフェッチします。詳細については、「 [リモートカタログの取得](./fetch-remote-catalog.md) 」を参照してください。

> **Note:**
>
> UGS を初期化する前に、[環境を設定](workflow#configure-your-environment-in-the-unity-editor) します。

初期化スクリプトで、Inspector で `PurchaseManager` コンポーネントを割り当てていることを確認します。`PurchaseManager` コンポーネントは、次の[リモートカタログ取得](./fetch-remote-catalog.md)ステップの一部として作成されます。

## Initialize services スクリプト例##initialize-services-example-script

以下のスクリプト例は、`ServiceOrchestrator` という名前です。

> **Important:**
>
> 推奨されるベスト プラクティスは、認証メソッドとして匿名ログインを使用しないことです。匿名ログインを使用すると、セッション トークンが紛失した後に購入が保持されないためです。アプリケーションで円滑なプラットフォーム固有のプロバイダーが利用できない場合は、[匿名認証とリンク](/authentication/anonymous-auth-and-linking.md)を参照してください。

```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 など)
        {
            // Compare error code to AuthenticationErrorCodes
            Debug.LogException(ex);
        }
        catch (RequestFailedException など)
        {
            // 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): Integrate D2C payment provider with IAP ワークフロー (D2C 支払いプロバイダーと IAP ワークフローの統合) ページに戻ります。
[Fetch your Remote Catalog](./fetch-remote-catalog.md): ワークフローの次のステップに進み、D2C支払いプロバイダーを設定します。
