Does the Unity Bug Reporter Compress the Project Then Upload It
Google Play Games plugin for Unity
Copyright (c) 2014 Google Inc. All rights reserved.
The Google Play Games plugin for Unity® is an open up-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®. Withal, this project is not in whatever style endorsed or supervised by Unity Technologies.
Unity® is a trademark of Unity Technologies.
iOS is a trademark of Apple tree, Inc.
Overview
The Google Play Games plugin for Unity allows you to admission the Google Play Games API through Unity's 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
- cloud relieve read/write
- bear witness built-in achievement/leaderboards UI
- events
- nearby connections
Observe: This version of the plugin no longer supports iOS. Google Play games services for iOS is deprecated, and is not likely to function equally expected. Do not use Google Play games services for iOS in new apps. See the deprecation proclamation weblog post for more details.
Features:
- easy GUI-oriented project setup (integrated into the Unity GUI)
- no need to override/customize the thespian Action
- no need to override/customize AndroidManifest.xml
Organization requirements:
-
Unity® 2017.4 or above.
-
To deploy on Android:
- Android SDK
- Android v4.0 or college
- Google Play Services library, version 11.half dozen or above
Upgrading
If yous take already integrated your project with a previous version of the plugin and wish to upgrade to a new version, please refer to the upgrade instructions.
Configure Your Game
To use the plugin, you must get-go configure your game in the Google Play Developer Console. Follow the instructions on creating a customer ID. Be particularly careful when inbound your packet proper noun and your certificate fingerprints, since mistakes on those screens can be difficult to recover from.
Copy the game resource from the console
Once you configure at least i resource (consequence, achievement, or leaderboard), re-create the resource configuration from the Google Play Programmer Console, and paste information technology into the setup configuration in Unity. To get the resources go to the Achievements tab, and then click on "Get resources" on the lesser of the list.
Then click the "Android department".
Select all the contents of the resources window, and copy 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 name - this is the name of the C# class to create, including namespace.
- Resource Definition - paste the resources data from the Play Games console here.
- Spider web client ID - this is the client ID of the linked web app. Information technology is simply needed if you lot take 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 y'all need an id token for the actor 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 certain to do the following if they are relevant to your game:
- Add together tester e-mail 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 achievements and leaderboards to your game in the Google Play Developer Console. For each accomplishment and leaderboard you configure, make sure to note the respective achievement ID or leaderboard ID, equally those volition exist needed when making the API calls. Achievement and leaderboard IDs are alphanumeric strings (due east.chiliad. "Cgkx9eiuwi8_AQ").
Add Events
Events allow you to rail user actions in your game and study on them with Analytics. Read more about how to configure and employ Events on Game Concepts - Events
Load Your Game Project
Next, load your game project into the Unity editor.
If you practice non take a game project to piece of work with, you can use the Minimal sample available in the samples directory. Using that sample will allow you to quickly test your setup and brand certain y'all tin can access the API.
If yous want to exam a larger sample after you lot are familiar with the plugin, try the CubicPilot game. More information nearly building the samples can be found in the samples README file.
Plugin Installation
To download the plugin, clone this Git repository into your file organisation (or download it as a Zilch file and unpack it). Then, expect for the unitypackage file in the electric current-build directory:
current-build/GooglePlayGamesPluginForUnity-X.YY.ZZ.unitypackage
To install the plugin, only open your game project in Unity and import that file into your project'south assets, equally you would any other Unity package. This is achieved through the Assets > Import Package > Custom Parcel carte du jour item (you can too attain this carte information technology by right-clicking the Assets binder).
Side by side, make sure your current build platform is ready to Android. From File > Build Settings… select Android and click Switch Platform. You should now encounter a new carte du jour item was added nether Window > Google Play Games. If you don't encounter the new menu items, refresh the assets by clicking Avails > Refresh and try again.
Android Setup
Next, set the path to your Android SDK installation in Unity. This is located in the preferences menu, under the External Tools section.
To configure your Unity game to run with Google Play Games on Android, first open up the Android SDK manager and verify that yous have downloaded the following packages. Depending on if yous are using the SDK manager from Android Studio, or using the standalone SDK managing director, the proper name of the components may be different.
- Google Play Services
- Android Support Library
- Local Maven repository for Support Libraries (Also known as Android Support Repository)
- Google Repository
- Android 6.0 (API 23) (this does not bear on the min SDK version).
Next, configure your game's bundle proper noun. To do this, click File > Build Settings, select the Android platform and click Actor Settings to show Unity's Role player Settings window. In that window, expect for the Bundle Identifier setting nether Other Settings. Enter your packet name there (for case com.instance.my.awesome.game).
In order to sign in to Play Game Services, you need to sign your APK file, brand certain that you are signing it with the right certificate, that is, the one that corresponds to the SHA1 document fingerprint you entered in the Developer Console during the setup.
Next, click the Window |Google Play Games|Setup - Android setup bill of fare item. This volition display the Android setup screen.
Enter the Constants class name. This is the proper name of the fully qualified class that will be updated (or created) which contains the IDs of the game resource. The format of the name is .. For instance, AwesomeGame.GPGSIds
Paste the resource definition data. This is the XML data from the Google Play Developer Console which contains the resource IDs also as the Application ID for Android.
This data is found in the Google Play Developer Console past clicking "Go resource" on whatever of the resource pages (e.g. Achievements or Leaderboards), then clicking Android.
After pasting the data into the text area, click the Setup button.
Note: If yous are using a web awarding or backend server with your game, yous can link the web application to the game to enable getting the role player'southward id token and/or electronic mail accost. To practise this, link a web application to the game in the Google Play Developer Panel, and enter the client id for the web application into the setup dialog.
Boosted instructions on building for Android on Windows
If you lot are using Windows, you must brand certain that your Java SDK installation tin be accessed by Unity. To exercise this:
- Prepare 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
binder to yourPATH
environment variable (for example,C:\Program Files\Coffee\jdk1.7.0_45\bin
) - Reboot.
How to edit environment variables: In Windows 2000/XP/Vista/7, right-click My Computer, then Properties, so become to Avant-garde System Backdrop (or System Backdrop and and then click the Advanced tab), then click Surround Variables. On Windows 8, press Windows Fundamental + W and search for surround variables For more information, consult the documentation for your version of Windows.
Run the Project
If you lot are working with the Smoketest sample, you should be able to build and run the project at this betoken. Yous will run into the automated sign-in effort, 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'due south 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 by Unity.
The standard API calls can exist accessed through the Social.Active object, which is a reference to an ISocialPlatform interface. The not-standard Google Play Games extensions can be accessed by casting the Social.Active object to the PlayGamesPlatform course, where the boosted methods are available.
Nearby Connections Configuration
In club to use nearby connections, a service id which uniquely identifies the gear up of applications that can collaborate needs to exist configured. This is done past clicking the Window > Google Play Games > Nearby Connections setup... menu item. This volition display the nearby connections setup screen. On this screen enter the service ID you want to employ. It should exist something that identifies your application, and follows the same rules every bit the bundle id (for example: com.instance.myawesomegame.nearby). Once y'all enter the id, press Setup.
To use nearby connections, the role player does non need to exist authenticated, and no Google Play Developer Console configuration is needed.
For detailed data on nearby connection usage, delight refer to nearby connections.
Sign in
A connectedness to Game services will exist automatically formed when your game is opened. One time the connexion is successful the player will be welcomed with a pop-upwards and your game is set up to brainstorm using the Games Unity Plugin.
Note: If a user has never used Google Play Games on this device, they volition exist automatically taken through one-fourth dimension setup operations such as creating a profile with the Play Games app.
In the Offset method of your script, listen to the result of the automatic sign-in attempt, fetch the authentication status and disable Play Games Services features if the user is not signed in.
using GooglePlayGames; public void Start() { PlayGamesPlatform.Instance.Cosign(ProcessAuthentication); } internal void ProcessAuthentication(SignInStatus status) { if (status == SignInStatus.Success) { // Keep with Play Games Services } else { // Disable your integration with Play Games Services or show a login button // to ask users to sign-in. Clicking it should phone call // PlayGamesPlatform.Example.ManuallyAuthenticate(ProcessAuthentication). } } }
The issue code is an enum, which gives y'all unlike failure reasons that volition help you understand sign-in failures better.
If you lot prefer using Unity's Social platform, then y'all can alternatively use the code block below.
using GooglePlayGames; public void Start() { PlayGamesPlatform.Activate(); Social.localUser.Cosign(ProcessAuthentication); }
Note that you cannot make any games API calls (unlock achievements, post scores, etc) until you lot get a successful return value from Authenticate, so it is skillful practise to put upward a standby screen until the callback is chosen, to make sure the user tin can't start playing the game until the authentication process completes.
Friends
Play Games Friends allows players to create and maintain a cantankerous-games friends list. You tin can asking admission 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 organization.
To enable Friends, employ the post-obit functions:
- View friends: Request admission to a thespian'southward friends list, then you tin add together their play games friends to your in-game friends list
- View a thespian profile: Let a role player view the Play Games contour of another player. This is essential so a actor knows who their friends are, and tin can connect to other Play Games players in your game. This will demand to be tied to a UI element to trigger the popup. Run across the friends guidelines for details.
Run across the best practices guidelines for instructions on how all-time to implement these APIs.
Note: To employ Friends, you need to update your PGS SDK to version 20.0.0
View friends
At that place are two ways 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" ); }
However, this phone call volition neglect if the electric current player has not withal granted permission to the game to access this information. Use GetLastLoadFriendsStatus
to check if LoadFriends
failed due to missing consent.
PlayGamesPlatform.Instance.GetLastLoadFriendsStatus((condition) => { // Cheque for consent if (status == LoadFriendsStatus.ResolutionRequired) { // Ask for resolution. } });
A game can enquire the current player to share the friends list by calling AskForLoadFriendsResolution
.
PlayGamesPlatform.Example.AskForLoadFriendsResolution((upshot) => { if (outcome == UIStatus.Valid) { // User agreed to share friends with the game. Reload friends. } else { // User doesn't agree to share the friends list. } });
This function volition testify 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 manner of loading friends is to apply LoadFriends
and LoadMoreFriends
:
PlayGamesPlatform.Example.LoadFriends(pageSize, forceReload, (status) => { // Check if the call is successful and if at that place are more friends to load. }); PlayGamesPlatform.Instance.LoadMoreFriends(pageSize, (status) => { // Bank check if there are more than friends to load. });
The pageSize
param represents the number of entries to request for this page. Note that if cached information already exists, the returned buffer may incorporate more than this size. The buffer is guaranteed to contain at least this many entries if the collection contains enough records. If forceReload
is set to truthful
, this call will articulate any locally-buried information and attempt to fetch the latest data from the server. This would unremarkably be used for actions similar a user-initiated refresh. Normally, this should be set to false
to gain the advantages of information caching.
If the callback returns LoadFriendsStatus.LoadMore
, then there are more friends to load. LoadFriendsStatus.ResolutionRequired
signals that the user has non shared the friends list and you lot can straight call PlayGamesPlatform.Instance.AskForLoadFriendsResolution
.
Determining friends list visibility
Utilise PlayGamesPlatform.Case.GetFriendsListVisibility
to check if the user has shared the friends list with the game. Possible return statuses are:
-
FriendsListVisibilityStatus.RequestRequired
indicates you must inquire for consent. -
FriendsListVisibilityStatus.Visible
indicates that loading the friends listing should succeed. -
FriendsListVisibilityStatus.Unknown
by and large shouldn't happen. Y'all can set upforceReload
to truthful to refresh the data.
PlayGamesPlatform.Example.GetFriendsListVisibility(forceReload, (friendsListVisibilityStatus) => {});
View a player profile
To add or remove a role player as a friend, use the show and compare profile function. This function triggers a lesser sheet dialog showing the Play Games contour of the user; call the function with the player Id of the requested histrion. If the histrion and friend take in-game nicknames, use them in the call to add more context to the profile UI:
PlayGamesPlatform.Instance.ShowCompareProfileWithAlternativeNameHintsUI( mFirstFriendId, /* otherPlayerInGameName= */ null, /* currentPlayerInGameName= */ zip, (upshot) => { // Contour comparison view has airtight. });
Role player Statistics
The Thespian Stats API let you lot tailor game experiences to specific segments of players and different stages of the player lifecycle. You can build tailored experiences for each player segment based on how players are progressing, spending, and engaging. For example, y'all tin can use this API to take proactive deportment to encourage a less active role player to re-engage with your game, such as by displaying and promoting new in-game items when the player signs in.
The callback takes two parameters:
- The result lawmaking less than or equal to nothing is success. Come across CommonStatusCodes for all values.
- The PlayerStats object of blazon GooglePlayGames.PlayGamesLocalUser.PlayerStats
For more than information see Player Stats.
The player stats are available after 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( "Information technology has been " + stats.DaysSinceLastPlayed + " days" ); } });
Revealing/Unlocking an Achievement
To unlock an achievement, use the Social.ReportProgress method with a progress value of 100.0f:
using GooglePlayGames; using UnityEngine.SocialPlatforms; ... // unlock achievement (accomplishment ID "Cfjewijawiu_QA") Social.ReportProgress( "Cfjewijawiu_QA" , 100 . 0 f, (bool success) => { // handle success or failure });
Notice that according to the expected behavior of Social.ReportProgress, a progress of 0.0f ways revealing the achievement and a progress of 100.0f means unlocking the achievement. Therefore, to reveal an achievement (that was previously hidden) without unlocking it, simply call Social.ReportProgress with a progress of 0.0f.
Incrementing an Achievement
If your achievement is incremental, the Play Games implementation of Social.ReportProgress will try to behave as closely as possible to the expected beliefs co-ordinate to Unity's social API, just may not be exact. For this reason, we recommend that you exercise not apply Social.ReportProgress for incremental achievements. Instead, use the PlayGamesPlatform.IncrementAchievement method, which is a Play Games extension.
using GooglePlayGames; using UnityEngine.SocialPlatforms; ... // increment achievement (achievement ID "Cfjewijawiu_QA") by 5 steps PlayGamesPlatform.Instance.IncrementAchievement( "Cfjewijawiu_QA" , 5, (bool success) => { // handle success or failure });
Posting a Score to a Leaderboard
To postal service 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 mail service a score and include a metadata tag use the Play Game Services instance directly:
using GooglePlayGames; using UnityEngine.SocialPlatforms; ... // mail score 12345 to leaderboard ID "Cfji293fjsie_QA" and tag "FirstDaily") Social.ReportScore(12345, "Cfji293fjsie_QA" , "FirstDaily" , (bool success) => { // handle success or failure });
Note that the platform and the server will automatically discard scores that are lower than the player's existing loftier score, so you lot tin submit scores freely without whatsoever checks to test whether or not the score is greater than the thespian's existing score.
Showing the Achievements UI
To show the built-in UI for all achievements, call Social.ShowAchievementsUI.
using GooglePlayGames; using UnityEngine.SocialPlatforms; ... // show achievements UI Social.ShowAchievementsUI();
Showing the Leaderboard UI
To show the congenital-in UI for all leaderboards, call Social.ShowLeaderboardUI.
using GooglePlayGames; using UnityEngine.SocialPlatforms; ... // bear witness leaderboard UI Social.ShowLeaderboardUI();
If you wish to testify a item leaderboard instead of all leaderboards, you tin can pass a leaderboard ID to the method. This, however, is a Play Games extension, so the Social.Agile object needs to be cast to a PlayGamesPlatform object starting time:
using GooglePlayGames; using UnityEngine.SocialPlatforms; ... // show leaderboard UI PlayGamesPlatform.Case.ShowLeaderboardUI( "Cfji293fjsie_QA" );
Accessing Leaderboard information
In that location 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 you to configure:
- The leaderboard Id
- The collection (social or public)
- The timeframe (daily, weekly, all-fourth dimension)
- The rank position to start retrieving scores.
- The number of scores (the default is 25).
- Filter past user id.
If the from parameter is not-positive, then the results returned are histrion-centered, meaning the scores effectually the current player'southward 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 information when accessing the leaderboard data.
PlayGamesPlatform.Instance.LoadScores( GPGSIds.leaderboard_leaders_in_smoketesting, LeaderboardStart.PlayerCentered, 100, LeaderboardCollection.Public, LeaderboardTimeSpan.AllTime, (information) => { mStatus = "Leaderboard information valid: " + data.Valid; mStatus += " \n approx:" + data.ApproximateCount + " take " + data.Scores.Length; });
The parameters for LoadScores() are:
- leaderboardId
- start position (top scores or player centered)
- row count
- leaderboard collection (social or public)
- time span (daily, weekly, all-fourth dimension)
- callback accepting a LeaderboardScoreData object.
The LeaderboardScoreData
class is used to render information back to the caller when loading scores. The members are: 1. Id - the leaderboard id two. Valid - true if the returned data is valid (the call was successful) three. Status - the ResponseStatus of the phone call 4. ApproximateCount - the approximate number of scores in the leaderboard v. Championship - the title of the leaderboard 6. PlayerScore - the score of the current player seven. Scores - the list of scores 8. PrevPageToken - a token that can be used to call LoadMoreScores()
to get the previous page of scores. ix. NextPageToken - a token that tin can exist used to telephone call LoadMoreScores()
to get the adjacent page of scores.
void GetNextPage(LeaderboardScoreData data) { PlayGamesPlatform.Instance.LoadMoreScores(data.NextPageToken, 10, (results) => { mStatus = "Leaderboard data valid: " + data.Valid; mStatus += " \n 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, use AskForLoadFriendsResolution
to request access.
Getting player names
Each score has the userId of the thespian that made the score. You can use Social.LoadUsers()
to load the player profile. Retrieve that the contents of the thespian contour are subject area to privacy settings of the players.
internal void LoadUsersAndDisplay(ILeaderboard lb) { // go the user ids List<string> userIds = new List<cord>(); foreach(IScore score in lb.scores) { userIds.Add(score.userID); } // load the profiles and display (or in this instance, 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 += " \due north " + score.formattedValue + " by " + (string)( (user != zilch) ? user.userName : "**unk_" + score.userID + "**" ); } Debug.log(status); }); }
Recording Events
Incrementing an event is very simple, merely call the following method:
using GooglePlayGames; ... // Increments the result with Id "YOUR_EVENT_ID" by 1 PlayGamesPlatform.Instance.Events.IncrementEvent( "YOUR_EVENT_ID" , 1);
This call is "burn down and forget", it volition handle batching and execution for you lot in the background.
Saving Game State to the Deject
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 = imitation; bool allowDelete = true; ISavedGameClient savedGameClient = PlayGamesPlatform.Example.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 } }
Opening a saved game
In guild 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, it is possible to run into conflicts in the state of the saved information. A conflict happens when a device attempts to relieve state to the deject but the data currently on the cloud was written by a different device. These conflicts need to be resolved when opening the saved game data. There are two open methods that handle conflict 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 manual resolution of the disharmonize.
See GooglePlayGames/BasicApi/SavedGame/ISavedGameClient.cs for more 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 (status == SavedGameRequestStatus.Success) { // handle reading or writing of saved game. } else { // handle error } }
Writing a saved game
Once the saved game file is opened, information technology can exist written to save the game state. 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 array of data
- a callback to call when the commit is consummate.
void SaveGame (ISavedGameMetadata game, byte[] savedData, TimeSpan totalPlaytime) { ISavedGameClient savedGameClient = PlayGamesPlatform.Instance.SavedGame; SavedGameMetadataUpdate.Builder builder = new SavedGameMetadataUpdate.Architect(); builder = builder .WithUpdatedPlayedTime(totalPlaytime) .WithUpdatedDescription( "Saved game at " + DateTime.Now()); if (savedImage != null) { // This assumes that savedImage is an case of Texture2D // and that yous take already called a function equivalent to // getScreenshot() to set savedImage // NOTE: see sample definition of getScreenshot() method below byte[] pngData = savedImage.EncodeToPNG(); builder = architect.WithUpdatedPngCoverImage(pngData); } SavedGameMetadataUpdate updatedMetadata = builder.Build(); savedGameClient.CommitUpdate(game, updatedMetadata, savedData, OnSavedGameWritten); } public void OnSavedGameWritten (SavedGameRequestStatus status, ISavedGameMetadata game) { if (condition == 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 peak left paw corner of screen and maps to summit // left paw corner of screenShot texture screenShot.ReadPixels( new Rect(0, 0, Screen.width, (Screen.width / 1024)* 700), 0, 0); return screenShot; }
Reading a saved game
In one case the saved game file is opened, it can be read to load the game state. This is washed by calling ReadBinaryData.
void LoadGameData (ISavedGameMetadata game) { ISavedGameClient savedGameClient = PlayGamesPlatform.Instance.SavedGame; savedGameClient.ReadBinaryData(game, OnSavedGameDataRead); } public void OnSavedGameDataRead (SavedGameRequestStatus condition, byte[] data) { if (status == SavedGameRequestStatus.Success) { // handle processing the byte array information } else { // handle error } }
Deleting a saved game
Once the saved game file is opened, it can exist deleted. This is done by calling Delete.
void DeleteGameData (string filename) { // Open the file to become the metadata. ISavedGameClient savedGameClient = PlayGamesPlatform.Example.SavedGame; savedGameClient.OpenWithAutomaticConflictResolution(filename, DataSource.ReadCacheOrNetwork, ConflictResolutionStrategy.UseLongestPlaytime, DeleteSavedGame); } public void DeleteSavedGame(SavedGameRequestStatus condition, ISavedGameMetadata game) { if (status == SavedGameRequestStatus.Success) { ISavedGameClient savedGameClient = PlayGamesPlatform.Instance.SavedGame; savedGameClient.Delete(game); } else { // handle error } }
Retrieving server authentication codes
In club to access Google APIs on a backend web server on behalf of the current player, you need to go an hallmark code from the client awarding and pass this to your spider web server application. This code tin then be exchanged for an access token to make calls to the various APIs. For more details on this period see: Google Sign-In for Websites.
To go the server side access code:
- Configure the web client id of the web awarding linked to your game in the Play Game Console.
- Call
PlayGamesPlatform.Example.RequestServerSideAccess
once the player is authenticated to go the server side admission lawmaking. - Laissez passer this code to your server awarding.
PlayGamesPlatform.Instance.RequestServerSideAccess( /* forceRefreshToken= */ fake, 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 utilize by using Proguard. Proguard will remove the Play Games Unity plugin code for features that are not used in your game, so your game ships with but the code that is needed and minimizes the size affect of using Play Games Services.
Additionally, it is possible to reduce the size of the entire Unity projection using Unity'southward Managed Lawmaking Stripping, which will compress your entire projection. This can be used in conjunction with Proguard.
Play Games Services Proguard configuration
- Go to
File > Build Settings > Thespian Settings
and clickPublishing Settings
section. ChooseProguard
forMinify > Release
. Then, enableUser Proguard File
. If yous want the plugin to be proguarded for debug apks also, you tin 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 you call PlayGamesPlatform.Actuate
, Google Play Games becomes your default social platform implementation, which ways that static calls to methods in Social
and Social.Active
volition be carried out by the Google Play Games plugin. This is the desired beliefs for most games using the plugin.
However, if for some reason yous wish to keep the default implementation accessible (for example, to use it to submit achievements and leaderboards to a unlike social platform), you can use the Google Play Games plugin without overriding the default i. To do this:
- Do non call
PlayGamesPlatform.Activate
- If
Xyz
is the proper noun of a method you wish to telephone call on theSocial
class, do not telephone callSocial.Xyz
. Instead, callPlayGamesPlatform.Case.Xyz
- Practise not use
Social.Active
when interacting with Google Play Games. Instead, usePlayGamesPlatform.Example
.
That way, you can fifty-fifty submit scores and achievements simultaneously to two or more social platforms:
// Submit achievement to original default social platform Social.ReportProgress( "MyAchievementIdHere" , 100 . 0 f, callback); // Submit achievement to Google Play PlayGamesPlatform.Instance.ReportProgress( "MyGooglePlayAchievementIdHere" , 100 . 0 f, callback);
Special Thanks
This department lists people who have contributed to this project past writing lawmaking, 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 back up library.
- pR0Ps for fixing an outcome where OnAchievementsLoaded was not accepting an OPERATION_DEFERRED result code every bit a success.
- friikyeu for helping debug an effect that caused API calls to exist queued upwardly rather than executed even when connected.
Source: https://github.com/playgameservices/play-games-plugin-for-unity
0 Response to "Does the Unity Bug Reporter Compress the Project Then Upload It"
Post a Comment