Unity Sign Game With Google Play Upload Certificate
Google Play Games plugin for Unity
Copyright (c) 2014 Google Inc. All rights reserved.
The Google Play Games plugin for Unity® is an open-source project whose goal is to provide a plugin that allows game developers to integrate with the Google Play Games API from a game written in Unity®. However, this project is not in any way endorsed or supervised by Unity Technologies.
Unity® is a trademark of Unity Technologies.
iOS is a trademark of Apple, Inc.
Overview
The Google Play Games plugin for Unity allows yous to access the Google Play Games API through Unity'due south social interface. The plugin provides support for the following features of the Google Play Games API:
- sign in
- friends
- unlock/reveal/increment achievement
- post score to leaderboard
- deject save read/write
- show built-in achievement/leaderboards UI
- events
- nearby connections
NOTICE: This version of the plugin no longer supports iOS. Google Play games services for iOS is deprecated, and is not likely to role as expected. Do not use Google Play games services for iOS in new apps. Run across the deprecation announcement weblog mail service for more than details.
Features:
- easy GUI-oriented project setup (integrated into the Unity GUI)
- no need to override/customize the player Activity
- no need to override/customize AndroidManifest.xml
System requirements:
-
Unity® 2017.4 or above.
-
To deploy on Android:
- Android SDK
- Android v4.0 or higher
- Google Play Services library, version 11.6 or above
Upgrading
If you accept already integrated your project with a previous version of the plugin and wish to upgrade to a new version, delight refer to the upgrade instructions.
Configure Your Game
To use the plugin, you must first configure your game in the Google Play Developer Panel. Follow the instructions on creating a customer ID. Exist particularly careful when entering your package name and your certificate fingerprints, since mistakes on those screens can be difficult to recover from.
Re-create the game resource from the console
Once you configure at least ane resource (event, accomplishment, or leaderboard), re-create the resource configuration from the Google Play Developer Console, and paste it into the setup configuration in Unity. To get the resources go to the Achievements tab, then click on "Get resources" on the bottom of the list.
And so click the "Android department".
Select all the contents of the resources window, and re-create them to the clipboard.
Paste the game resource into the plugin setup dialog
Back in Unity, open the setup dialog Window > Google Play Games > Setup... > Android Setup
- Enter the directory to save constants - Enter the folder for the constants file.
- Constants class proper name - this is the name of the C# class to create, including namespace.
- Resource Definition - paste the resource data from the Play Games console here.
- Web customer ID - this is the client ID of the linked web app. Information technology is only needed if you lot have a web-based backend for your game and need a server auth code to be exchanged for an access token by the backend server, or if you need an id token for the player to make other, non-game, API calls.
The setup process volition configure your game with the client id and generate a C# class that contains constants for each of your resources.
Setup Checklist
Make sure to exercise the post-obit if they are relevant to your game:
- Add tester email addresses to the testing section of your game on the Play Games Panel.
- The SHA1 fingerprint used to create the linked Android app is from the keystore used to sign the Unity awarding.
Add Achievements and Leaderboards
Add together achievements and leaderboards to your game in the Google Play Developer Console. For each accomplishment and leaderboard you configure, make sure to note the corresponding achievement ID or leaderboard ID, equally those will exist needed when making the API calls. Achievement and leaderboard IDs are alphanumeric strings (e.g. "Cgkx9eiuwi8_AQ").
Add Events
Events allow you to rails user deportment in your game and written report on them with Analytics. Read more than near how to configure and use Events on Game Concepts - Events
Load Your Game Project
Next, load your game project into the Unity editor.
If yous do not have a game project to work with, you can employ the Minimal sample available in the samples directory. Using that sample volition allow you to apace test your setup and brand sure you can access the API.
If you want to examination a larger sample later on yous are familiar with the plugin, effort the CubicPilot game. More information nearly building the samples can be constitute in the samples README file.
Plugin Installation
To download the plugin, clone this Git repository into your file organisation (or download it as a Aught file and unpack information technology). And then, look for the unitypackage file in the current-build directory:
current-build/GooglePlayGamesPluginForUnity-X.YY.ZZ.unitypackage
To install the plugin, simply open your game project in Unity and import that file into your project'due south avails, every bit yous would whatsoever other Unity packet. This is achieved through the Assets > Import Package > Custom Package carte du jour particular (you can besides reach this card information technology by right-clicking the Assets folder).
Adjacent, make sure your current build platform is prepare to Android. From File > Build Settings… select Android and click Switch Platform. You should now see a new menu item was added under Window > Google Play Games. If you don't see the new menu items, refresh the assets past clicking Assets > Refresh and endeavor again.
Android Setup
Next, fix the path to your Android SDK installation in Unity. This is located in the preferences bill of fare, under the External Tools department.
To configure your Unity game to run with Google Play Games on Android, first open up the Android SDK director and verify that you accept downloaded the following packages. Depending on if you are using the SDK manager from Android Studio, or using the standalone SDK manager, the name of the components may be different.
- Google Play Services
- Android Support Library
- Local Maven repository for Support Libraries (Also known as Android Back up Repository)
- Google Repository
- Android 6.0 (API 23) (this does non bear on the min SDK version).
Next, configure your game'south package proper noun. To do this, click File > Build Settings, select the Android platform and click Player Settings to evidence Unity'southward Player Settings window. In that window, expect for the Package Identifier setting under Other Settings. Enter your package proper noun there (for example com.instance.my.awesome.game).
In lodge to sign in to Play Game Services, you need to sign your APK file, make sure that you are signing it with the correct document, that is, the one that corresponds to the SHA1 certificate fingerprint yous entered in the Programmer Panel during the setup.
Next, click the Window |Google Play Games|Setup - Android setup menu item. This will display the Android setup screen.
Enter the Constants class name. This is the name of the fully qualified class that will be updated (or created) which contains the IDs of the game resources. The format of the name is .. For example, AwesomeGame.GPGSIds
Paste the resource definition data. This is the XML information from the Google Play Developer Console which contains the resource IDs as well as the Application ID for Android.
This data is found in the Google Play Developer Console by clicking "Get resources" on any of the resource pages (e.g. Achievements or Leaderboards), so clicking Android.
Later on pasting the data into the text surface area, click the Setup push button.
Notation: If you are using a web application or backend server with your game, you can link the spider web application to the game to enable getting the histrion'south id token and/or email address. To do this, link a web application to the game in the Google Play Developer Console, and enter the client id for the web awarding into the setup dialog.
Boosted instructions on building for Android on Windows
If you are using Windows, you must make sure that your Java SDK installation tin can exist accessed by Unity. To exercise this:
- Set the JAVA_HOME environment variable to your Java SDK installation path (for example,
C:\Program Files\Java\jdk1.7.0_45
). - Add the Java SDK's
bin
folder to yourPATH
environs variable (for case,C:\Program Files\Java\jdk1.7.0_45\bin
) - Reboot.
How to edit surroundings variables: In Windows 2000/XP/Vista/7, right-click My Figurer, then Properties, then go to Advanced Organization Properties (or Organization Properties and then click the Advanced tab), then click Environment Variables. On Windows eight, press Windows Key + W and search for environs variables For more than data, consult the documentation for your version of Windows.
Run the Projection
If you are working with the Smoketest sample, you should be able to build and run the project at this point. Yous volition come across the automated sign-in attempt, when Smoketest starts.
To build and run on Android, click File > Build Settings, select the Android platform, then Switch to Platform, then Build and Run.
ISocialPlatform Compliance
The Google Play Games plugin implements Unity'southward social interface, for compatibility with games that already use that interface when integrating with other platforms. However, some features are unique to Play Games and are offered as extensions to the standard social interface provided past Unity.
The standard API calls tin be accessed through the Social.Active object, which is a reference to an ISocialPlatform interface. The non-standard Google Play Games extensions can be accessed by casting the Social.Active object to the PlayGamesPlatform grade, where the boosted methods are available.
Nearby Connections Configuration
In order to use nearby connections, a service id which uniquely identifies the set of applications that can collaborate needs to be configured. This is done by clicking the Window > Google Play Games > Nearby Connections setup... menu particular. This will brandish the nearby connections setup screen. On this screen enter the service ID you lot want to apply. It should be something that identifies your application, and follows the same rules as the bundle id (for instance: com.example.myawesomegame.nearby). One time you enter the id, press Setup.
To utilize nearby connections, the histrion does not demand to be authenticated, and no Google Play Programmer Panel configuration is needed.
For detailed information on nearby connection usage, please refer to nearby connections.
Sign in
A connexion to Game services will exist automatically formed when your game is opened. Once the connection is successful the histrion will be welcomed with a pop-up and your game is ready to begin using the Games Unity Plugin.
Note: If a user has never used Google Play Games on this device, they will be automatically taken through one-time setup operations such as creating a profile with the Play Games app.
In the Start method of your script, listen to the upshot of the automatic sign-in endeavour, fetch the hallmark status and disable Play Games Services features if the user is non signed in.
using GooglePlayGames; public void First() { PlayGamesPlatform.Instance.Authenticate(ProcessAuthentication); } internal void ProcessAuthentication(SignInStatus condition) { if (status == SignInStatus.Success) { // Continue with Play Games Services } else { // Disable your integration with Play Games Services or show a login push // to inquire users to sign-in. Clicking it should phone call // PlayGamesPlatform.Case.ManuallyAuthenticate(ProcessAuthentication). } } }
The result code is an enum, which gives you unlike failure reasons that will help you empathise sign-in failures better.
If you prefer using Unity's Social platform, then you can alternatively use the code block below.
using GooglePlayGames; public void Kickoff() { PlayGamesPlatform.Activate(); Social.localUser.Authenticate(ProcessAuthentication); }
Note that you cannot brand any games API calls (unlock achievements, post scores, etc) until you go a successful return value from Authenticate, so it is skillful practice to put upwards a standby screen until the callback is called, to make sure the user tin't start playing the game until the authentication process completes.
Friends
Play Games Friends allows players to create and maintain a cross-games friends listing. You can request access to this friends listing to help your players play your game with their friends. See the Friends concept page for more details on the friends system.
To enable Friends, use the following functions:
- View friends: Request access to a actor's friends list, so you tin add together their play games friends to your in-game friends list
- View a player profile: Permit a role player view the Play Games profile of some other player. This is essential so a player knows who their friends are, and tin connect to other Play Games players in your game. This volition need to be tied to a UI element to trigger the popup. See the friends guidelines for details.
See the best practices guidelines for instructions on how best to implement these APIs.
Note: To use Friends, you lot demand to update your PGS SDK to version 20.0.0
View friends
There are ii means to load friends, either using the ISocial
framework or directly with PlayGamesPlatform
.
Loading friends with the ISocial framework
Social.localUser.LoadFriends((success) => { Debug.Log( "Friends loaded OK: " + ok)); foreach(IUserProfile p in Social.localUser.friends) { Debug.Log(p.userName + " is a friend" ); }
Nonetheless, this call will neglect if the electric current player has not notwithstanding granted permission to the game to access this information. Use GetLastLoadFriendsStatus
to check if LoadFriends
failed due to missing consent.
PlayGamesPlatform.Instance.GetLastLoadFriendsStatus((condition) => { // Check for consent if (condition == LoadFriendsStatus.ResolutionRequired) { // Ask for resolution. } });
A game tin can ask the current player to share the friends list by calling AskForLoadFriendsResolution
.
PlayGamesPlatform.Case.AskForLoadFriendsResolution((issue) => { if (result == UIStatus.Valid) { // User agreed to share friends with the game. Reload friends. } else { // User doesn't agree to share the friends listing. } });
This part will bear witness the advisable platform-specific friends sharing UI. This UI asks the player if they want to share their friends with the game.
Loading friends with PlayGamesPlatform
Another fashion of loading friends is to use LoadFriends
and LoadMoreFriends
:
PlayGamesPlatform.Instance.LoadFriends(pageSize, forceReload, (status) => { // Check if the call is successful and if there are more friends to load. }); PlayGamesPlatform.Example.LoadMoreFriends(pageSize, (status) => { // Bank check if there are more friends to load. });
The pageSize
param represents the number of entries to request for this page. Note that if cached data already exists, the returned buffer may comprise more than this size. The buffer is guaranteed to contain at least this many entries if the collection contains plenty records. If forceReload
is set to true
, this call will clear whatever locally-cached information and try to fetch the latest data from the server. This would commonly be used for actions like a user-initiated refresh. Normally, this should exist ready to false
to gain the advantages of data caching.
If the callback returns LoadFriendsStatus.LoadMore
, then in that location are more friends to load. LoadFriendsStatus.ResolutionRequired
signals that the user has not shared the friends list and you can directly phone call PlayGamesPlatform.Instance.AskForLoadFriendsResolution
.
Determining friends listing visibility
Apply PlayGamesPlatform.Case.GetFriendsListVisibility
to check if the user has shared the friends listing with the game. Possible render statuses are:
-
FriendsListVisibilityStatus.RequestRequired
indicates you must ask for consent. -
FriendsListVisibilityStatus.Visible
indicates that loading the friends listing should succeed. -
FriendsListVisibilityStatus.Unknown
by and large shouldn't happen. You tin setforceReload
to truthful to refresh the data.
PlayGamesPlatform.Instance.GetFriendsListVisibility(forceReload, (friendsListVisibilityStatus) => {});
View a player profile
To add or remove a player as a friend, use the show and compare profile office. This function triggers a bottom sheet dialog showing the Play Games profile of the user; phone call the part with the player Id of the requested player. If the player and friend have in-game nicknames, use them in the call to add together more than context to the profile UI:
PlayGamesPlatform.Instance.ShowCompareProfileWithAlternativeNameHintsUI( mFirstFriendId, /* otherPlayerInGameName= */ cypher, /* currentPlayerInGameName= */ null, (result) => { // Profile comparison view has closed. });
Player Statistics
The Player Stats API let you tailor game experiences to specific segments of players and different stages of the thespian lifecycle. You can build tailored experiences for each player segment based on how players are progressing, spending, and engaging. For case, you can use this API to take proactive actions to encourage a less active histrion to re-engage with your game, such as past displaying and promoting new in-game items when the player signs in.
The callback takes two parameters:
- The outcome lawmaking less than or equal to cypher is success. See CommonStatusCodes for all values.
- The PlayerStats object of type GooglePlayGames.PlayGamesLocalUser.PlayerStats
For more information see Actor Stats.
The actor stats are available later authenticating:
((PlayGamesLocalUser)Social.localUser).GetStats((rc, stats) => { // -1 means cached stats, 0 is succeess // see CommonStatusCodes for all values. if (rc <= 0 && stats.HasDaysSinceLastPlayed()) { Debug.Log( "It has been " + stats.DaysSinceLastPlayed + " days" ); } });
Revealing/Unlocking an Accomplishment
To unlock an achievement, use the Social.ReportProgress method with a progress value of 100.0f:
using GooglePlayGames; using UnityEngine.SocialPlatforms; ... // unlock accomplishment (achievement ID "Cfjewijawiu_QA") Social.ReportProgress( "Cfjewijawiu_QA" , 100 . 0 f, (bool success) => { // handle success or failure });
Detect that co-ordinate to the expected behavior of Social.ReportProgress, a progress of 0.0f means revealing the accomplishment and a progress of 100.0f means unlocking the achievement. Therefore, to reveal an achievement (that was previously subconscious) without unlocking it, simply telephone call Social.ReportProgress with a progress of 0.0f.
Incrementing an Accomplishment
If your achievement is incremental, the Play Games implementation of Social.ReportProgress will try to comport every bit closely as possible to the expected behavior co-ordinate to Unity'south social API, but may not be exact. For this reason, we recommend that yous do not use Social.ReportProgress for incremental achievements. Instead, use the PlayGamesPlatform.IncrementAchievement method, which is a Play Games extension.
using GooglePlayGames; using UnityEngine.SocialPlatforms; ... // increase achievement (achievement ID "Cfjewijawiu_QA") by five steps PlayGamesPlatform.Instance.IncrementAchievement( "Cfjewijawiu_QA" , 5, (bool success) => { // handle success or failure });
Posting a Score to a Leaderboard
To post a score to a leaderboard, call Social.ReportScore.
using GooglePlayGames; using UnityEngine.SocialPlatforms; ... // post score 12345 to leaderboard ID "Cfji293fjsie_QA") Social.ReportScore(12345, "Cfji293fjsie_QA" , (bool success) => { // handle success or failure });
To post a score and include a metadata tag utilise the Play Game Services instance direct:
using GooglePlayGames; using UnityEngine.SocialPlatforms; ... // post score 12345 to leaderboard ID "Cfji293fjsie_QA" and tag "FirstDaily") Social.ReportScore(12345, "Cfji293fjsie_QA" , "FirstDaily" , (bool success) => { // handle success or failure });
Notation that the platform and the server volition automatically discard scores that are lower than the player'southward existing high score, so yous tin submit scores freely without any checks to test whether or not the score is greater than the player's existing score.
Showing the Achievements UI
To testify the built-in UI for all achievements, phone call Social.ShowAchievementsUI.
using GooglePlayGames; using UnityEngine.SocialPlatforms; ... // show achievements UI Social.ShowAchievementsUI();
Showing the Leaderboard UI
To show the built-in UI for all leaderboards, call Social.ShowLeaderboardUI.
using GooglePlayGames; using UnityEngine.SocialPlatforms; ... // bear witness leaderboard UI Social.ShowLeaderboardUI();
If you wish to show a detail leaderboard instead of all leaderboards, you tin can pass a leaderboard ID to the method. This, still, is a Play Games extension, so the Social.Active object needs to be cast to a PlayGamesPlatform object starting time:
using GooglePlayGames; using UnityEngine.SocialPlatforms; ... // prove leaderboard UI PlayGamesPlatform.Example.ShowLeaderboardUI( "Cfji293fjsie_QA" );
Accessing Leaderboard data
There are 2 methods to retrieving the leaderboard score data.
Using Social.ILeaderboard
This method uses the ILeaderboard interface to define the telescopic and filters for getting the data. This approach allows yous to configure:
- The leaderboard Id
- The collection (social or public)
- The timeframe (daily, weekly, all-fourth dimension)
- The rank position to offset retrieving scores.
- The number of scores (the default is 25).
- Filter by user id.
If the from parameter is not-positive, then the results returned are player-centered, meaning the scores around the electric current player's score are returned.
ILeaderboard lb = PlayGamesPlatform.Instance.CreateLeaderboard(); lb.id = "MY_LEADERBOARD_ID" ; lb.LoadScores(ok => { if (ok) { LoadUsersAndDisplay(lb); } else { Debug.Log( "Error retrieving leaderboardi" ); } });
Using PlayGamesPlatform.LoadScores()
This method uses the PlayGamesPlatform directly. This approach provides additional flexibility and data when accessing the leaderboard data.
PlayGamesPlatform.Instance.LoadScores( GPGSIds.leaderboard_leaders_in_smoketesting, LeaderboardStart.PlayerCentered, 100, LeaderboardCollection.Public, LeaderboardTimeSpan.AllTime, (data) => { mStatus = "Leaderboard data valid: " + data.Valid; mStatus += " \n approx:" + data.ApproximateCount + " accept " + information.Scores.Length; });
The parameters for LoadScores() are:
- leaderboardId
- beginning position (top scores or actor centered)
- row count
- leaderboard drove (social or public)
- time bridge (daily, weekly, all-time)
- callback accepting a LeaderboardScoreData object.
The LeaderboardScoreData
grade is used to return data back to the caller when loading scores. The members are: 1. Id - the leaderboard id 2. Valid - true if the returned data is valid (the call was successful) 3. Status - the ResponseStatus of the call 4. ApproximateCount - the approximate number of scores in the leaderboard 5. Championship - the title of the leaderboard vi. PlayerScore - the score of the current histrion 7. Scores - the list of scores 8. PrevPageToken - a token that can be used to call LoadMoreScores()
to become the previous page of scores. nine. NextPageToken - a token that can be used to call LoadMoreScores()
to get the adjacent page of scores.
void GetNextPage(LeaderboardScoreData data) { PlayGamesPlatform.Instance.LoadMoreScores(information.NextPageToken, 10, (results) => { mStatus = "Leaderboard data valid: " + data.Valid; mStatus += " \due north approx:" + information.ApproximateCount + " have " + data.Scores.Length; }); }
This call may fail when trying to load friends with ResponseCode.ResolutionRequired
if the user has not shared their friends list with the game. In this example, employ AskForLoadFriendsResolution
to asking access.
Getting histrion names
Each score has the userId of the player that made the score. You can use Social.LoadUsers()
to load the thespian contour. Remember that the contents of the player contour are bailiwick to privacy settings of the players.
internal void LoadUsersAndDisplay(ILeaderboard lb) { // get the user ids Listing<cord> userIds = new List<string>(); foreach(IScore score in lb.scores) { userIds.Add(score.userID); } // load the profiles and brandish (or in this case, log) Social.LoadUsers(userIds.ToArray(), (users) => { string status = "Leaderboard loading: " + lb.title + " count = " + lb.scores.Length; foreach(IScore score in lb.scores) { IUserProfile user = FindUser(users, score.userID); condition += " \n " + score.formattedValue + " by " + (string)( (user != aught) ? user.userName : "**unk_" + score.userID + "**" ); } Debug.log(status); }); }
Recording Events
Incrementing an event is very simple, just call the following method:
using GooglePlayGames; ... // Increments the issue with Id "YOUR_EVENT_ID" by 1 PlayGamesPlatform.Instance.Events.IncrementEvent( "YOUR_EVENT_ID" , 1);
This call is "fire and forget", it will handle batching and execution for you lot in the groundwork.
Saving Game Country to the Cloud
For details on saved games concepts and APIs delight refer to the documentation.
Displaying saved games UI
The standard UI for selecting or creating a saved game entry is displayed by calling:
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 abolish or error } }
Opening a saved game
In order to read or write data to a saved game, the saved game needs to be opened. Since the saved game state is cached locally on the device and saved to the cloud, information technology is possible to encounter conflicts in the state of the saved data. A conflict happens when a device attempts to salve land to the cloud merely the data currently on the deject was written by a different device. These conflicts need to be resolved when opening the saved game information. There are ii open methods that handle disharmonize resolution, the offset OpenWithAutomaticConflictResolution accepts a standard resolution strategy type and automatically resolves the conflicts. The other method, OpenWithManualConflictResolution accepts a callback method to allow the transmission resolution of the conflict.
See GooglePlayGames/BasicApi/SavedGame/ISavedGameClient.cs for more than details on these methods.
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 (condition == SavedGameRequestStatus.Success) { // handle reading or writing of saved game. } else { // handle error } }
Writing a saved game
Once the saved game file is opened, it can be written to save the game country. This is done by calling CommitUpdate. There are four parameters to CommitUpdate:
- the saved game metadata passed to the callback passed to one of the Open calls.
- the updates to make to the metadata.
- the actual byte assortment of information
- a callback to call when the commit is complete.
void SaveGame (ISavedGameMetadata game, byte[] savedData, TimeSpan totalPlaytime) { ISavedGameClient savedGameClient = PlayGamesPlatform.Instance.SavedGame; SavedGameMetadataUpdate.Builder architect = new SavedGameMetadataUpdate.Builder(); builder = architect .WithUpdatedPlayedTime(totalPlaytime) .WithUpdatedDescription( "Saved game at " + DateTime.Now()); if (savedImage != null) { // This assumes that savedImage is an case of Texture2D // and that you have already called a function equivalent to // getScreenshot() to set savedImage // NOTE: run into sample definition of getScreenshot() method below byte[] pngData = savedImage.EncodeToPNG(); builder = builder.WithUpdatedPngCoverImage(pngData); } SavedGameMetadataUpdate updatedMetadata = architect.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 summit // left manus corner of screenShot texture screenShot.ReadPixels( new Rect(0, 0, Screen.width, (Screen.width / 1024)* 700), 0, 0); return screenShot; }
Reading a saved game
One time the saved game file is opened, information technology can be read to load the game state. This is done by calling ReadBinaryData.
void LoadGameData (ISavedGameMetadata game) { ISavedGameClient savedGameClient = PlayGamesPlatform.Instance.SavedGame; savedGameClient.ReadBinaryData(game, OnSavedGameDataRead); } public void OnSavedGameDataRead (SavedGameRequestStatus status, byte[] information) { if (status == SavedGameRequestStatus.Success) { // handle processing the byte array data } else { // handle error } }
Deleting a saved game
Once the saved game file is opened, information technology can exist deleted. This is done by calling Delete.
void DeleteGameData (string filename) { // Open the file to get the metadata. ISavedGameClient savedGameClient = PlayGamesPlatform.Case.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 fault } }
Retrieving server authentication codes
In order to admission Google APIs on a backend web server on behalf of the current thespian, you need to get an authentication code from the client application and pass this to your web server application. This code tin can then be exchanged for an admission token to make calls to the various APIs. For more details on this flow see: Google Sign-In for Websites.
To get the server side access lawmaking:
- Configure the web client id of the web awarding linked to your game in the Play Game Console.
- Call
PlayGamesPlatform.Instance.RequestServerSideAccess
in one case the player is authenticated to go the server side access code. - Pass this code to your server application.
PlayGamesPlatform.Case.RequestServerSideAccess( /* forceRefreshToken= */ false, code - > { // send code to server });
Decreasing apk size
It is possible to decrease the size of the Play Games Services Unity Plugin past removing code for the Play Games Services features that your game doesn't utilise past using Proguard. Proguard will remove the Play Games Unity plugin lawmaking for features that are not used in your game, and then your game ships with simply the code that is needed and minimizes the size impact of using Play Games Services.
Additionally, information technology is possible to reduce the size of the entire Unity project using Unity'southward Managed Code Stripping, which will compress your entire project. This tin be used in conjunction with Proguard.
Play Games Services Proguard configuration
- Become to
File > Build Settings > Player Settings
and clickPublishing Settings
section. ChooseProguard
forMinify > Release
. Then, enableUser Proguard File
. If y'all want the plugin to be proguarded for debug apks as well, yous can chooseProguard
forMinify > Debug
. - Copy the content of the proguard configuration into
Assets/Plugins/Android/proguard-user.txt
.
(Advanced) Using the Plugin Without Overriding the Default Social Platform
When yous call PlayGamesPlatform.Actuate
, Google Play Games becomes your default social platform implementation, which means that static calls to methods in Social
and Social.Agile
will exist carried out by the Google Play Games plugin. This is the desired behavior for near games using the plugin.
Nonetheless, if for some reason you wish to go on the default implementation attainable (for case, to use it to submit achievements and leaderboards to a different social platform), you can use the Google Play Games plugin without overriding the default one. To do this:
- Exercise not telephone call
PlayGamesPlatform.Activate
- If
Xyz
is the name of a method you wish to call on theSocial
class, do not callSocial.Xyz
. Instead, callPlayGamesPlatform.Instance.Xyz
- Practise not use
Social.Active
when interacting with Google Play Games. Instead, usePlayGamesPlatform.Instance
.
That way, you can even submit scores and achievements simultaneously to ii or more social platforms:
// Submit achievement to original default social platform Social.ReportProgress( "MyAchievementIdHere" , 100 . 0 f, callback); // Submit achievement to Google Play PlayGamesPlatform.Example.ReportProgress( "MyGooglePlayAchievementIdHere" , 100 . 0 f, callback);
Special Thanks
This section lists people who have contributed to this projection past writing code, improving documentation or fixing bugs.
- Dgizusse for figuring out that setting JAVA_HOME is necessary on Windows.
- antonlicht for fixing a bug with the parameter type of showErrorDialog on the support library.
- pR0Ps for fixing an outcome where OnAchievementsLoaded was not accepting an OPERATION_DEFERRED consequence code every bit a success.
- friikyeu for helping debug an outcome that caused API calls to be queued up rather than executed even when continued.
Source: https://github.com/playgameservices/play-games-plugin-for-unity
0 Response to "Unity Sign Game With Google Play Upload Certificate"
Publicar un comentario