PlayFab Unity SDK

repository·master·Indexed 19 days ago

https://github.com/playfab/unitysdk

The PlayFab Unity SDK provides tools and APIs to integrate PlayFab backend services, including authentication, player data, and economy, into Unity games. It features the PlayFabClientAPI for client-side operations, optional Editor Extensions (EdEx) for simplified installation and configuration, and a PluginManager for implementing custom JSON serializers (ISerializerPlugin) and network HTTP clients (IPlayFabTransportPlugin).

Tokens
5.5K
Snippets
10
Records
23
Agent score
65%

What's inside playfab-unitysdk

  1. Identify the required PlayFab Unity SDK packages

    master

    The PlayFab Unity SDK is distributed via several .unitypackage files. The core package is mandatory for all integrations.

    • UnitySDK.unitypackage: The core SDK used for accessing the PlayFab Service. This is mandatory for almost all use cases.
    • JsonDotNetWrapper.unitypackage: A wrapper that allows you to use Json.net with the PlayFab SDK. While Json.net is no longer a hard requirement, this package is useful if you want to maintain compatibility with existing Json.net implementations within the PlayFab JSON wrapper system.
    • UnityPlayFabPaperTrail.unitypackage: An older, beta demonstration package (circa 2016) that integrates Papertrail logging. Note that this package is out-of-date and its exact capabilities are undocumented.
  2. Configure PlayFabSettings.TitleId

    master

    The PlayFabSettings.TitleId is a mandatory configuration step. Every PlayFab developer creates a title in the Game Manager, and you must code that specific TitleId into your game. This allows the client to know which PlayFab data to access. If this is not set correctly, all API calls will fail.

    PlayFabSettings.TitleId = "YOUR_TITLE_ID_HERE";
  3. Configure HTTP Request Implementation

    master

    You can choose how the SDK handles HTTPS REST calls via the PlayFabSharedSettings scriptable object or the EdEx panel (Settings -> Project).

    OptionDescription
    UnityWebRequestDefault choice. Uses Unity's built-in engine class. Recommended for most modern projects and platforms.
    HttpWebRequestUses the C# HttpRequest library. It is multi-threaded (requests may not run on the main thread). Allows customization of timeouts via PlayFabSettings.
    UnityWwwOnly for older engine versions (pre-2018.2). Uses the Unity WWW class.
    CustomHttpFor implementing a custom ITransportPlugin. Use PluginManager.SetPlugin with a PluginContract of PlayFab_Transport to register your plugin. Reference PlayFabUnityHttp.cs or PlayFabWebRequest.cs for implementation patterns.
  4. Extend the SDK with PluginManager

    master

    The PlayFab Unity SDK uses the PluginManager class to allow developers to provide custom implementations for core SDK components. This is useful if you need to use a specific JSON serializer or a custom network HTTP client for your PlayFab backend communication.

    Currently, the SDK supports two plugin interfaces:

    • PlayFab.ISerializerPlugin: Allows you to provide a custom JSON serializer.
    • PlayFab.IPlayFabTransportPlugin: Allows you to provide a custom network HTTP client specific to the PlayFab backend.

    Prerequisites:

    • The SDK must be installed and set up.
    • PlayFab Title ID must be initialized (e.g., via PlayFabSettings.TitleId).
  5. Understand PlayFab API request and callback patterns

    master

    PlayFab API calls in Unity follow an asynchronous pattern using request objects and callback functions.

    Request Objects

    Most API methods require input parameters packed into a specific request object (e.g., LoginWithCustomIDRequest). These objects contain a mix of mandatory and optional parameters. For example, LoginWithCustomIDRequest requires a CustomId to uniquely identify a player.

    Asynchronous Callbacks

    API calls are non-blocking. When you call a method like PlayFabClientAPI.LoginWithCustomID, your game continues to run normally while the request is processed in the background. Once the server response is parsed, PlayFab invokes your provided callback functions within a Unity Coroutine.

    Common callback signatures include:

    • Success Callback: Receives a result object (e.g., LoginResult) containing requested information.
    • Failure Callback: Receives a PlayFabError object. You should always handle failures using error.GenerateErrorReport() to debug issues like incorrect TitleId, missing parameters, or connectivity problems.
  6. Use custom JSON serializers via ISerializer

    master

    If you prefer to continue using JSON.net or another third-party library, you can implement the ISerializer interface. The SDK provides an ISerializer framework that allows you to wrap any JSON library and integrate it into the PlayFab workflow.

    To use JSON.net specifically, you can download the ISerializer package for JSON.net from the official source.

  7. Install PlayFab Unity Editor Extensions (Recommended)

    master

    The PlayFab Unity Editor Extensions (EdEx) provide a user interface to simplify downloading, installing, configuring, and upgrading the PlayFab SDK. This is the simplest way to get started.

    1. Download the Editor Extensions package.
    2. Open your Unity project.
    3. In the Unity editor, navigate to Assets > Import Package > Custom Package and select the downloaded .unitypackage.
    4. In the import window, select Import.
    5. Once installed, a PlayFab panel will appear in the Unity editor for account login and SDK management.
  8. Manual Installation of PlayFab Unity SDK

    master

    Advanced users can install the SDK manually by extracting the package directly into their project.

    1. Download the SDK Asset Package (UnitySDK.unitypackage).
    2. Important for Updates: Before importing, delete existing PlayFab directories to avoid compiler or runtime errors:
      • Delete {ProjectLocation}/assets/PlayFab*/ directories.
      • For very old SDKs, also delete PlayFab-specific files in {ProjectLocation}/assets/Plugins/.
    3. Unpack the .unitypackage into your project.

    Note: You can also copy contents from the ExampleTestProject/Assets directory in the repository for a reference setup.

  9. Register custom plugins with PluginManager

    master

    To activate your custom plugins, use PluginManager.SetPlugin before calling any other PlayFab APIs. This is typically done during your application's initialization phase (e.g., in a Start method).

    Use the PluginContract enum to specify which component you are replacing:

    • PluginContract.PlayFab_Serializer for the JSON serializer.
    • PluginContract.PlayFab_Transport for the network transport.
    public void Start()
    {
        // Optionally set your own custom JSON serializer
        PluginManager.SetPlugin(new MyJsonSerializer(), PluginContract.PlayFab_Serializer);
    
        // Optionally set your own custom HTTP network client
        PluginManager.SetPlugin(new MyNetworkTransportClient(), PluginContract.PlayFab_Transport);
    
        // ...
    }
  10. Update or Install SDK via Editor Extensions

    master

    If you have already installed the Editor Extensions, you can manage the SDK directly through the UI:

    1. Log in to the Editor Extensions panel.
    2. If the SDK is missing or an update is available, an orange install/update button will appear in the panel.
  11. Install the PlayFab UnitySDK

    master

    To use PlayFab in Unity, you must import the provided .unitypackage.

    1. Download the PlayFab UnitySdk Unitypackage from https://aka.ms/PlayFabUnitySdk.
    2. In the Unity Editor, locate the Project window.
    3. Import the package using one of these methods:
      • Drag and Drop: Drag the PlayFab UnitySDK.unitypackage file directly onto the Project panel.
      • Manual Import: Right-click in an empty space in the Project panel and select Import Package -> Custom Package..., then select the file.
    4. When the import window appears, click Import.
  12. Make your first PlayFab API call

    master

    This guide demonstrates how to authenticate a player using LoginWithCustomID.

    Implementation Steps

    1. Create a new C# script named PlayFabLogin in your Unity project.
    2. Replace the script contents with the implementation below.
    3. Crucial: Replace the placeholder TitleId with your actual Title ID from the PlayFab Game Manager.
    4. Create a new GameObject in your Unity scene and attach the PlayFabLogin script to it.
    5. Press Play in the Unity Editor to execute the call.

    Code Example

    using PlayFab;
    using PlayFab.ClientModels;
    using UnityEngine;
    
    public class PlayFabLogin : MonoBehaviour
    {
        public void Start()
        {
            // Replace with your actual TitleId from PlayFab Game Manager
            PlayFabSettings.TitleId = "144"; 
    
            var request = new LoginWithCustomIDRequest { CustomId = "GettingStartedGuide", CreateAccount = true};
            PlayFabClientAPI.LoginWithCustomID(request, OnLoginSuccess, OnLoginFailure);
        }
    
        private void OnLoginSuccess(LoginResult result)
        {
            Debug.Log("Congratulations, you made your first successful API call!");
        }
    
        private void OnLoginFailure(PlayFabError error)
        {
            Debug.LogWarning("Something went wrong with your first API call.  :(");
            Debug.LogError("Here's some debug information:");
            Debug.LogError(error.GenerateErrorReport());
        }
    }
    using PlayFab;
    using PlayFab.ClientModels;
    using UnityEngine;
    
    public class PlayFabLogin : MonoBehaviour
    {
        public void Start()
        {
            PlayFabSettings.TitleId = "144"; 
    
            var request = new LoginWithCustomIDRequest { CustomId = "GettingStartedGuide", CreateAccount = true};
            PlayFabClientAPI.LoginWithCustomID(request, OnLoginSuccess, OnLoginFailure);
        }
    
        private void OnLoginSuccess(LoginResult result)
        {
            Debug.Log("Congratulations, you made your first successful API call!");
        }
    
        private void OnLoginFailure(PlayFabError error)
        {
            Debug.LogWarning("Something went wrong with your first API call.  :(");
            Debug.LogError("Here's some debug information:");
            Debug.LogError(error.GenerateErrorReport());
        }
    }