Initialize Unity Gaming Services

Before you begin your multiplayer game, you must first initialize Unity Gaming Services for your project.

  1. In the Unity Editor, go to the Project window, then select Assets > Scripts.

  2. Right-click (macOS: Ctrl+click) Scripts.

  3. Select Create > Scripting > MonoBehaviour Script.

  4. Name the script SessionManager.

  5. Right-click (macOS: Ctrl+click) in the Hierarchy window and select Create Empty.

  6. Enter SessionManager as the name.

  7. Select this new SessionManager GameObject.

  8. In its Inspector window, select Add Component.

  9. Select your SessionManager script.

  10. In the Project window, double-click the SessionManager script. The script opens in your preselected IDE.

  11. Replace the contents of SessionManager.cs with the following code:

    using UnityEngine;
    using Unity.Services.Core;
    using System;
    using Unity.Services.Authentication;
    
    public class SessionManager : MonoBehaviour
    {
        async void Start()
        {
    
    	    try
    	    {
    	     await UnityServices.InitializeAsync();
    	     await AuthenticationService.Instance.SignInAnonymouslyAsync();
    	     Debug.Log($"Sign in anonymously succeeded! PlayerID: {AuthenticationService.Instance.PlayerId}");
    	    }
    	    catch (Exception e)
    	    {
    	     Debug.LogException(e);
    	    }
        }
    
    }

    In the above code:

    • The line await UnityServices.InitializeAsync(); initializes Unity Gaming Services SDKs.
    • The line await AuthenticationService.Instance.SignInAnonymouslyAsync(); anonymously authenticates the player.

    The Authentication SDK supports anonymous authentication and external authentication solutions for supported platforms, including mobile and PC. Refer to Approaches to authentication for more details. Anonymous authentication requires no special configuration, making it easier to use than external authentication and more suitable for prototyping.

    As the developer, you must authenticate your players after initializing Multiplayer Services in your code.