Juegos guardados en Unity

En este tema, se describe cómo usar los juegos guardados para los Servicios de juego de Play en juegos de Unity.

Antes de comenzar

  • Configura tu proyecto y el complemento de Google Play Juegos para Unity. Si deseas obtener más detalles, consulta la guía de introducción.

  • Habilita los juegos guardados. Si deseas obtener más detalles, consulta la guía de juegos guardados.

Cómo mostrar la IU de juegos guardados

A fin de mostrar o modificar la IU estándar para seleccionar o crear una entrada de juego guardado, debes hacer lo siguiente:

    void ShowSelectUI() {
        uint maxNumToDisplay = 5;
        bool allowCreateNew = false;
        bool allowDelete = true;

        ISavedGameClient savedGameClient = PlayGamesPlatform.Instance.SavedGame;
        savedGameClient.ShowSelectSavedGameUI("Select saved game",
            maxNumToDisplay,
            allowCreateNew,
            allowDelete,
            OnSavedGameSelected);
    }


    public void OnSavedGameSelected (SelectUIStatus status, ISavedGameMetadata game) {
        if (status == SelectUIStatus.SavedGameSelected) {
            // handle selected game save
        } else {
            // handle cancel or error
        }
    }

Cómo abrir un juego guardado

A fin de poder leer o escribir datos en un juego guardado, este debe estar abierto. Dado que el estado del juego guardado se almacena tanto en la caché local del dispositivo como en la nube, es posible que se generen conflictos en el estado de los datos guardados. Se producirá un conflicto cuando un dispositivo intente guardar el estado en la nube, pero otro dispositivo haya escrito los datos que se encuentren en ella. Estos conflictos se deben resolver cuando se abran los datos del juego guardado.

Existen 2 métodos abiertos que controlan la resolución de conflictos. El primero, OpenWithAutomaticConflictResolution, acepta un tipo de estrategia de resolución estándar y resuelve los conflictos automáticamente. El otro, OpenWithManualConflictResolution, acepta un método de devolución de llamada para permitir la resolución manual del conflicto.

Consulta GooglePlayGames/BasicApi/SavedGame/ISavedGameClient.cs a fin de obtener más información sobre estos métodos.

    void OpenSavedGame(string filename) {
        ISavedGameClient savedGameClient = PlayGamesPlatform.Instance.SavedGame;
        savedGameClient.OpenWithAutomaticConflictResolution(filename, DataSource.ReadCacheOrNetwork,
            ConflictResolutionStrategy.UseLongestPlaytime, OnSavedGameOpened);
    }

    public void OnSavedGameOpened(SavedGameRequestStatus status, ISavedGameMetadata game) {
        if (status == SavedGameRequestStatus.Success) {
            // handle reading or writing of saved game.
        } else {
            // handle error
        }
    }

Cómo escribir un juego guardado

Una vez que se abre el archivo del juego guardado, se puede escribir a fin de guardar el estado del juego. Para ello, se debe llamar a CommitUpdate. Existen cuatro parámetros para CommitUpdate:

  1. los metadatos del juego guardado que se pasan a la devolución de llamada pasada a una de las llamadas abiertas
  2. las actualizaciones que se deben hacer en los metadatos
  3. el array de bytes real de los datos
  4. una devolución de llamada que se realizará cuando se complete la confirmación
    void SaveGame (ISavedGameMetadata game, byte[] savedData, TimeSpan totalPlaytime) {
        ISavedGameClient savedGameClient = PlayGamesPlatform.Instance.SavedGame;

        SavedGameMetadataUpdate.Builder builder = new SavedGameMetadataUpdate.Builder();
        builder = builder
            .WithUpdatedPlayedTime(totalPlaytime)
            .WithUpdatedDescription("Saved game at " + DateTime.Now());
        if (savedImage != null) {
            // This assumes that savedImage is an instance of Texture2D
            // and that you have already called a function equivalent to
            // getScreenshot() to set savedImage
            // NOTE: see sample definition of getScreenshot() method below
            byte[] pngData = savedImage.EncodeToPNG();
            builder = builder.WithUpdatedPngCoverImage(pngData);
        }
        SavedGameMetadataUpdate updatedMetadata = builder.Build();
        savedGameClient.CommitUpdate(game, updatedMetadata, savedData, OnSavedGameWritten);
    }

    public void OnSavedGameWritten (SavedGameRequestStatus status, ISavedGameMetadata game) {
        if (status == SavedGameRequestStatus.Success) {
            // handle reading or writing of saved game.
        } else {
            // handle error
        }
    }

    public Texture2D getScreenshot() {
        // Create a 2D texture that is 1024x700 pixels from which the PNG will be
        // extracted
        Texture2D screenShot = new Texture2D(1024, 700);

        // Takes the screenshot from top left hand corner of screen and maps to top
        // left hand corner of screenShot texture
        screenShot.ReadPixels(
            new Rect(0, 0, Screen.width, (Screen.width/1024)*700), 0, 0);
        return screenShot;
    }

Cómo leer un juego guardado

Una vez que el archivo del juego guardado se abre, este se puede leer a fin de cargar el estado del juego. Para ello, se debe llamar a ReadBinaryData.

    void LoadGameData (ISavedGameMetadata game) {
        ISavedGameClient savedGameClient = PlayGamesPlatform.Instance.SavedGame;
        savedGameClient.ReadBinaryData(game, OnSavedGameDataRead);
    }

    public void OnSavedGameDataRead (SavedGameRequestStatus status, byte[] data) {
        if (status == SavedGameRequestStatus.Success) {
            // handle processing the byte array data
        } else {
            // handle error
        }
    }

Cómo borrar un juego guardado

Una vez que se abre el archivo del juego guardado, se lo puede borrar. Para ello, se debe llamar a Delete.

    void DeleteGameData (string filename) {
        // Open the file to get the metadata.
        ISavedGameClient savedGameClient = PlayGamesPlatform.Instance.SavedGame;
        savedGameClient.OpenWithAutomaticConflictResolution(filename, DataSource.ReadCacheOrNetwork,
            ConflictResolutionStrategy.UseLongestPlaytime, DeleteSavedGame);
    }

    public void DeleteSavedGame(SavedGameRequestStatus status, ISavedGameMetadata game) {
        if (status == SavedGameRequestStatus.Success) {
            ISavedGameClient savedGameClient = PlayGamesPlatform.Instance.SavedGame;
            savedGameClient.Delete(game);
        } else {
            // handle error
        }
    }