Integrar o SDK do Google Play Games para PC com o Unity

Este guia fornece instruções detalhadas para integrar o SDK do Google Play Games para PC ao seu projeto do Unity.

Etapa 1: fazer o download do SDK

Faça o download da versão mais recente do pacote do Unity usando o link de download.

Download: SDK do Unity para PC do Play Games

Etapa 2: importar o pacote

O SDK é distribuído como um arquivo tar compatível com o Unity Package Manager (UPM). Para mais informações, consulte Instalar um pacote do UPM de um arquivo tar local.

Etapa 3: configurar as configurações de build

Para verificar se as bibliotecas nativas são carregadas corretamente, configure seu projeto para usar o back-end de script IL2CPP e segmentar a arquitetura correta.

  1. Crie um perfil de build com o Windows como plataforma.

  2. Selecione as configurações de plataforma como Windows. Para a arquitetura, use as opções:

    • Intel de 64 bits (recomendado)
    • Intel 32 bits

    Observação:a plataforma Google Play Games no PC é executada em um ambiente de 64 bits. Você pode criar seu jogo como 32 bits (x86) ou 64 bits (x64).

  3. Configure o Scripting Backend como IL2CPP. Para mais informações, consulte Como criar um projeto com IL2CPP.

    • Defina o Nível de compatibilidade da API como .NET Standard 2.0 (ou .NET Framework).

Etapa 4: criar o manifesto do aplicativo

Antes de usar o SDK no jogo, associe o executável do jogo ao nome do pacote do Google Play que você reivindicou no Play Console. Para isso, adicione um arquivo manifest.xml no mesmo diretório do executável do jogo.

Observação:esta é uma etapa manual que precisa ser realizada.

  1. Para criar o arquivo executável do jogo, selecione Arquivo > Criar e executar ou clique em Ctrl+B.
  2. Abra um editor de texto e crie um arquivo chamado manifest.xml.
  3. Copie e cole o seguinte código XML no arquivo:

    <?xml version="1.0" encoding="utf-8"?>
    <?Manifest version="1">
       <?Application>
         <?PackageName>com.example.package<?/PackageName>
       <?/Application>
    <?/Manifest>

  4. Salve o arquivo como manifest.xml.

  5. Mova esse arquivo para a mesma pasta do arquivo executável do jogo criado.

    Exemplo: se o jogo estiver em Builds/MyGame.exe, o manifesto precisará estar em Builds/manifest.xml.

Etapa 5: inicializar o SDK

É necessário inicializar o SDK antes de acessar qualquer recurso, como faturamento ou integridade. Use o PlayPcSdkFactory para criar o manipulador de inicialização e iniciar a conexão.

Crie um novo script C#, por exemplo, SdkInitialization.cs, e adicione o seguinte código:

using UnityEngine;
using System;
using System.Threading.Tasks;
// Import the SDK namespaces
using PlayPcSdkManaged.Initialization;
using PlayPcSdkManaged.Unity;

public class GooglePlayPCSDKInit : MonoBehaviour
{
    // Prevent double-initialization if this script is reloaded
    private static bool _isInitialized = false;

    private void Start()
    {
        // Use the "Safe Runner" pattern to fire the async method
        _ = InitializeSdkAsync();
    }

    private async Task InitializeSdkAsync()
    {
        if (_isInitialized)
        {
            Debug.LogWarning("Google Play PC SDK is already initialized. Skipping.");
            return;
        }

        try
        {
            Debug.Log("Initializing Google Play PC SDK...");

            // 1. Get the Unity-specific initialization handler from the factory
            var initHandler = PlayPcSdkFactory.InitializationHandler;

            // 2. Call InitializeAsync to start the connection
            var result = await GooglePlayInitialization.InitializeAsync(initHandler);

            // 3. Check the result
            if (result.IsOk)
            {
                _isInitialized = true;
                Debug.Log("<color=green>Google Play PC SDK Initialized Successfully!</color>");
                // You can now create BillingClient or IntegrityClient instances
            }
            else
            {
                Debug.LogError($"<color=red>Initialization Failed!</color>");
                Debug.LogError($"Error Code: {result.Code}");
                Debug.LogError($"Message: {result.ErrorMessage}");
            }
        }
        catch (Exception ex)
        {
            // Catch unexpected crashes or task failures
            Debug.LogError($"Exception during initialization: {ex.Message}");
            Debug.LogException(ex);
        }
    }
}

Anexe esse script a um GameObject na sua primeira cena. Ao executar o jogo, verifique se a mensagem "SDK Initialized Successfully!" aparece no console.