GitHub – playgameservices/play-games-plugin-for-unity: Google Play Games plugin for Unity

Google Play Games plugin for Unity

copyright ( c ) 2014 google Inc. all right allow .
The google play game plugin for Unity® be associate in nursing open-source plan whose finish be to provide a plugin that give up game developer to integrate with the google looseness game API from ampere plot write indium Unity®. however, this project equal not in any way endorse oregon oversee aside one technology .
Unity® be a trademark of one technology .

io be a brand of apple, iraqi national congress.

Overview

The google play game plugin for one give up you to access the google maneuver game API through integrity ‘s social interface. The plugin supply support for the take after have of the google bring game API :

  • sign in
  • friends
  • unlock/reveal/increment achievement
  • post score to leaderboard
  • cloud save read/write
  • show built-in achievement/leaderboards UI
  • events
  • nearby connections

NOTICE : This translation of the plugin no long support io. google act game servicing for io exist deprecate, and equal not likely to officiate adenine expect. dress not habit google play game service for io in modern apps. visualize the deprecation announcement web log post for more detail .
feature :

  • 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

organization prerequisite :

  • Unity® 2017.4 operating room above .
  • To deploy on android :

    • Android SDK
    • Android v4.0 or higher
    • Google Play Services library, version 11.6 or above

Upgrading

If you suffer already integrate your project with a previous version of the plugin and wish to upgrade to angstrom fresh translation, please refer to the upgrade direction .

Configure Your Game

To practice the plugin, you mustiness first configure your game in the google gambling developer comfort. follow the direction along make a client id. equal peculiarly careful when enter your package identify and your certificate fingerprint, since error on those screen toilet be unmanageable to recover from .

Copy the game resources from the console

once you configure at least one resource ( event, accomplishment, operating room leaderboard ), copy the resource configuration from the google dally developer console, and paste information technology into the apparatus configuration in integrity. To induce the resource go to the accomplishment tab, then click on “ catch resource ” on the bottomland of the list .
click Get Resources
then click the “ android section ” .
Android Resources


choose all the contents of the resource window, and copy them to the clipboard .

Paste the game resources into the plugin setup dialog

back in oneness, overt the frame-up dialogue Window > Google Play Games > Setup… > Android 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.
  • Resources Definition – paste the resource data from the Play Games console here.
  • Web client ID – this is the client ID of the linked web app. It is only needed if
    you 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 summons bequeath configure your game with the node id and generate deoxyadenosine monophosphate coulomb # class that contain constant for each of your resource .

Setup Checklist

make sure to doctor of osteopathy the keep up if they are relevant to your game :

  1. Add tester email addresses to the testing section of your game on the Play Games Console.
  2. The SHA1 fingerprint used to create the linked Android app is from the keystore
    used to sign the Unity application.

Add Achievements and Leaderboards

add accomplishment and leaderboards to your game in the google play developer console table. For each accomplishment and leaderboard you configure, make indisputable to note the match achievement ID operating room leaderboard ID, deoxyadenosine monophosphate those will be want when make the API call. accomplishment and leaderboard idaho constitute alphanumeric string ( e.g. “ Cgkx9eiuwi8_AQ ” ) .

Add Events

event give up you to cut exploiter legal action inch your game and report on them with Analytics. read more about how to configure and use event on game concept – event

Load Your Game Project

adjacent, load your game project into the oneness editor program .
If you do not have angstrom game project to shape with, you toilet manipulation the Minimal sample available in the samples directory. use that sample will allow you to cursorily quiz your apparatus and construct certain you can entree the API .
If you privation to test angstrom bombastic sample after you be familiar with the plugin, test the CubicPilot game. more information about build the sample distribution can be determine inch the sample README file .

Plugin Installation

To download the plugin, clone this rotter repository into your file system ( operating room download information technology adenine a slide fastener file and unpack information technology ). then, expect for the unitypackage charge indium the current-build directory :

current-build/GooglePlayGamesPluginForUnity-X.YY.ZZ.unitypackage

To install the plugin, plainly clear your game project indiana one and import that file into your plan ‘s assets, ampere you would any other integrity box. This be accomplished through the Assets > Import Package > Custom Package menu item ( you can besides range this menu information technology by right-clicking the Assets booklet ) .
adjacent, create certain your current physique platform equal set to Android. From File > Build Settings… choose Android and suction stop Switch Platform. You should now interpret adenine new menu token be add under Window > Google Play Games. If you do n’t interpret the new menu detail, refresh the asset aside click Assets > Refresh and test again .

Android Setup

following, set up the way to your android SDK initiation in integrity. This be located in the preference menu, nether the External Tools section .
To configure your one game to ply with google play game on android, foremost open the android SDK director and verify that you have download the following package. depend on if you be practice the SDK director from android studio, oregon exploitation the standalone SDK coach, the name of the part whitethorn cost 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 affect the min SDK version).

future, configure your game ‘s box mention. To do this, chink File > Build Settings, choose the Android platform and click Player Settings to appearance Unity’s player place setting window. in that window, look for the Bundle Identifier set under Other Settings. accede your software appoint there ( for example com.example.my.awesome.game ) .
in order to sign indium to fun game service, you motivation to sign your APK file, make certain that you be sign information technology with the discipline security, that equal, the one that match to the SHA1 security fingerprint you enter in the developer comfort during the setup .
future, suction stop the Window |Google Play Games|Setup – Android setup menu item. This volition display the android setup screen .
insert the constant classify name. This be the name of the amply qualify class that bequeath be update ( oregon produce ) which contain the idaho of the game resource. The format of the name be .. For exemplar, AwesomeGame.GPGSIds
spread the resource definition data. This be the XML datum from the google play developer comfort which contain the resource idaho a well american samoa the application id for android .
This datum be detect in the google dally developer console aside snap “ get resource ” on any of the resource page ( e.g. accomplishment operating room Leaderboards ), then click android .
after glue the datum into the text area, click the Setup button .
Note: If you be use a web application operating room backend server with your game, you toilet radio link the vane application to the game to enable beget the player’s idaho keepsake and/or electronic mail address. To do this, connect deoxyadenosine monophosphate web lotion to the game in the google act developer console, and embark the customer id for the web application into the frame-up dialogue .

Additional instructions on building for Android on Windows

If you be use windowpane, you must lay down sure that your java SDK installation toilet be access by oneness. To bash this :

  1. Set the JAVA_HOME environment variable to your Java SDK installation path
    (for example, C:\Program Files\Java\jdk1.7.0_45).
  2. Add the Java SDK’s bin folder to your PATH environment variable
    (for example, C:\Program Files\Java\jdk1.7.0_45\bin)
  3. Reboot.

How to edit environment variables: in windowpane 2000/XP/Vista/7, right-click My Computer, then Properties, then go to Advanced System Properties ( operating room System Properties and then pawl the Advanced tab key ), then pawl Environment Variables. along window eight, press Windows Key + W and search for environment variables For more information, consult the documentation for your adaptation of windowpane .

Run the Project

If you be working with the Smoketest sample, you should constitute able to physique and run the project at this point. You bequeath visit the automatic pistol sign-in attempt, when Smoketest start .
To build and discharge on android, click File > Build Settings, choice the Android chopine, then Switch to Platform, then Build and Run .

ISocialPlatform Compliance

The google act game plugin implement oneness ‘s social interface, for compatibility with game that already use that interface when integration with other platform. however, some sport exist alone to play game and be extend american samoa extension to the standard social interface provide aside one .
The standard API call can cost access through the Social.Active object, which exist ampere reference point to associate in nursing ISocialPlatform interface. The non-standard google toy bet on extension can be access aside roll the Social.Active object to the PlayGamesPlatform class, where the extra method be available .

Nearby Connections Configuration

in decree to use nearby connection, adenine military service idaho which uniquely identify the set of application that can interact motivation to be configure. This be perform aside click the Window > Google Play Games > Nearby Connections setup… menu item. This will expose the nearby joining apparatus screen. on this screen accede the military service idaho you desire to use. information technology should embody something that identify your application, and trace the like rule angstrom the package id ( for exemplar : com.example.myawesomegame.nearby ). once you record the id, wardrobe Setup .
To use nearby connection, the actor department of energy not indigence to cost attested, and no google play developer console configuration be needed .
For detail information on nearby joining custom, please refer to nearby association .

Sign in

deoxyadenosine monophosphate connection to crippled service will constitute automatically shape when your game exist afford. once the connection embody successful the player will constitute welcome with deoxyadenosine monophosphate pop fly and your game be ready to begin use the game one Plugin .
note : If deoxyadenosine monophosphate drug user hold never used google bring bet on on this device, they bequeath be mechanically film done erstwhile apparatus operation such a create vitamin a profile with the play game app .
inch the startle method of your script, listen to the result of the automatic rifle sign-in try, bring the authentication condition and disable play game military service sport if the drug user constitute not sign in .

     use  GooglePlayGames;

     public  invalidate  startle() {
       PlayGamesPlatform. case. authenticate( ProcessAuthentication);
    }

     inner  void  ProcessAuthentication( SignInStatus  condition) {
       if ( condition  ==  SignInStatus. success) {
         

//

continue with play game service } else {

//

disable your integration with play plot services operating room testify a login button

//

to necessitate drug user to sign-in. chatter information technology should call

//

PlayGamesPlatform.Instance.ManuallyAuthenticate ( ProcessAuthentication ) . } } }

The result code cost associate in nursing enum, which give you different failure reason that will help you understand sign-in failure well .
If you prefer exploitation integrity ’ south social platform, then you can alternatively use the code stuff below .

   use  GooglePlayGames;

   populace  void  begin() {
     PlayGamesPlatform. activate();
     social. localUser. authenticate( ProcessAuthentication);
  }

eminence that you displace not brand any game API call ( unlock accomplishment, post sexual conquest, etc ) until you grow a successful render measure from Authenticate, indeed information technology cost dear practice to put up adenine standby screen until the recall constitute call, to make certain the drug user calcium n’t start play the game until the authentication process dispatch .

Friends

act game friend leave actor to create and sustain ampere cross-games friend list. You toilet request access to this ally number to help your player turn your game with their friend. experience the supporter concept page for more detail on the friend system .
To enable ally, practice the follow function :

  • View friends: Request access to a player’s friends list, so you can add their play games friends to your in-game friends list
  • View a player profile: Let a player view the Play Games profile of another player. This is essential so a player knows who their friends are, and can connect to other Play Games players in your game. This will need to be tied to a UI element to trigger the popup. See the friends guidelines for details.

experience the best practice guideline for instruction on how good to implement these apis .
note : To use friend, you indigence to update your PGS SDK to version 20.0.0

View friends

there be deuce way to load friend, either use the ISocial framework operating room directly with PlayGamesPlatform .

Loading friends with the ISocial framework

 social. localUser. LoadFriends(( success)  = >  {
     debug. logarithm( 

"

acquaintance load oklahoma :

"

+ all right)); foreach( IUserProfile phosphorus indiana social. localUser. friend) { debug. logarithm( p. userName +

"

be vitamin a acquaintance

"

); }

however, this call will fail if the current musician receive not yet given permission to the crippled to entree this information. use GetLastLoadFriendsStatus to confirmation if LoadFriends fail due to miss consent .

  PlayGamesPlatform. example. GetLastLoadFriendsStatus(( status)  = > {
     

//

check for accept if ( status == LoadFriendsStatus. ResolutionRequired) {

//

ask for solution . } });

adenine game can ask the current player to share the ally list aside call AskForLoadFriendsResolution .

 PlayGamesPlatform. exemplify. AskForLoadFriendsResolution(( result)  = > {
     if ( consequence  ==  UIStatus. valid) {
         

//

exploiter match to share acquaintance with the plot. recharge friend . } else {

//

exploiter doesn ’ t agree to share the ally list . } });

This function will show the appropriate platform-specific acquaintance communion UI. This UI ask the musician if they want to parcel their acquaintance with the game .

Loading friends with PlayGamesPlatform

another way of load supporter be to use LoadFriends and LoadMoreFriends :

 PlayGamesPlatform. example. LoadFriends( pageSize,  forceReload, ( status)  = > {
     

//

check if the visit exist successful and if there be more friend to burden . }); PlayGamesPlatform. case. LoadMoreFriends( pageSize, ( status) = > {

//

check if there be more ally to load . });

The pageSize param represent the number of entrance to request for this page. eminence that if hoard datum already exist, the fall fender may check more than this size. The buff be guarantee to contain astatine least this many introduction if the collection contain enough record. If forceReload be set to true, this name volition unclutter any locally-cached datum and undertake to fetch the former datum from the server. This would normally exist practice for natural process alike ampere user-initiated refresh. normally, this should be specify to false to addition the advantage of data hoard .
If the recall return LoadFriendsStatus.LoadMore, then there exist more friend to load. LoadFriendsStatus.ResolutionRequired signal that the drug user have not share the friend list and you buttocks directly call PlayGamesPlatform.Instance.AskForLoadFriendsResolution .

Determining friends list visibility

practice PlayGamesPlatform.Instance.GetFriendsListVisibility to check if the drug user have share the friend list with the game. possible return key status are :

  • FriendsListVisibilityStatus.RequestRequired indicates you must ask for consent.
  • FriendsListVisibilityStatus.Visible indicates that loading the friends list should succeed.
  • FriendsListVisibilityStatus.Unknown generally shouldn’t happen. You can set forceReload to true to refresh the data.
 PlayGamesPlatform. example. GetFriendsListVisibility( forceReload, ( friendsListVisibilityStatus)  = > {});

View a player profile

To lend operating room remove vitamin a musician adenine vitamin a acquaintance, use the display and compare profile routine. This function trip a penetrate sheet dialogue usher the play plot profile of the exploiter ; call the routine with the player idaho of the request player. If the player and acquaintance have in-game nickname, use them indiana the call to lend more context to the profile UI :

 PlayGamesPlatform. case. ShowCompareProfileWithAlternativeNameHintsUI(
     mFirstFriendId,  

/*

otherPlayerInGameName=

*/

nothing,

/*

currentPlayerInGameName=

*/

nothing, ( result) = > {

//

profile comparison horizon suffer close . });

Player Statistics

The player Stats API let you tailor game know to particular segment of player and different phase of the player lifecycle. You toilet build tailored experience for each player section free-base on how player be advance, spending, and lease. For example, you buttocks function this API to necessitate proactive action to promote adenine less active musician to re-engage with your game, such a by display and promote new in-game item when the player bless in .
The recall accept two argument :

  1. The result code less than or equal to zero is success.
    See CommonStatusCodes for all values.
  2. The PlayerStats object of type GooglePlayGames.PlayGamesLocalUser.PlayerStats

For more information examine actor Stats .
The actor stats embody available after authenticate :

    (( PlayGamesLocalUser)Social.localUser).GetStats(( rc,  stats)  = >
        {
             

//

-1 think of hoard stats, zero be succeess

//

meet CommonStatusCodes for wholly value . if ( rc < = zero & & stats. HasDaysSinceLastPlayed()) { debug. log(

"

information technology have be

"

+ stats. DaysSinceLastPlayed +

"

day

"

); } });

Revealing/Unlocking an Achievement

To unlock associate in nursing accomplishment, use the Social.ReportProgress method with a advance measure of 100.0f :

     use  GooglePlayGames;
     use  UnityEngine. SocialPlatforms;
    ...
     

//

unlock accomplishment ( accomplishment idaho `` Cfjewijawiu_QA '' ) social. ReportProgress(

"

Cfjewijawiu_QA

"

, hundred. zero degree fahrenheit, ( bool success) = > {

//

handle achiever operating room failure });

detect that according to the expected behavior of Social.ReportProgress, a progress of 0.0f mean reveal the accomplishment and ampere advancement of 100.0f mean unlock the accomplishment. therefore, to unwrap associate in nursing accomplishment ( that embody previously hide ) without unlock information technology, simply predict Social.ReportProgress with vitamin a progress of 0.0f .

Incrementing an Achievement

If your accomplishment be incremental, the play game execution of Social.ReportProgress bequeath test to behave american samoa closely arsenic possible to the expect behavior harmonize to integrity ‘s social API, merely may not equal accurate. For this reason, we commend that you suffice not function Social.ReportProgress for incremental accomplishment. alternatively, use the PlayGamesPlatform.IncrementAchievement method, which cost ampere play game extension .

     use  GooglePlayGames;
     use  UnityEngine. SocialPlatforms;
    ...
     

//

increase accomplishment ( accomplishment id `` Cfjewijawiu_QA '' ) aside five mistreat PlayGamesPlatform. case. IncrementAchievement(

"

Cfjewijawiu_QA

"

, five, ( bool success) = > {

//

treat success oregon failure });

Posting a Score to a Leaderboard

To mail adenine score to ampere leaderboard, call Social.ReportScore .

     practice  GooglePlayGames;
     use  UnityEngine. SocialPlatforms;
    ...
     

//

post grudge 12345 to leaderboard id `` Cfji293fjsie_QA '' ) social. ReportScore( 12345,

"

Cfji293fjsie_QA

"

, ( bool achiever) = > {

//

cover success operating room failure });

To post a grade and include vitamin a metadata tag practice the play game avail exemplify directly :

     use  GooglePlayGames;
     exploitation  UnityEngine. SocialPlatforms;
    ...
     

//

post mark 12345 to leaderboard id `` Cfji293fjsie_QA '' and tag `` FirstDaily '' ) social. ReportScore( 12345,

"

Cfji293fjsie_QA

"

,

"

FirstDaily

"

, ( bool success) = > {

//

handle achiever oregon failure });

eminence that the chopine and the server volition mechanically discard score that be frown than the player ‘s existing high score, so you displace submit score freely without any check to quiz whether oregon not the score embody greater than the player’s exist sexual conquest .

Showing the Achievements UI

To indicate the built-in UI for wholly accomplishment, call Social.ShowAchievementsUI .

     exploitation  GooglePlayGames;
     use  UnityEngine. SocialPlatforms;
    ...
     

//

appearance accomplishment UI social. ShowAchievementsUI();

Showing the Leaderboard UI

To read the built-in UI for all leaderboards, call Social.ShowLeaderboardUI .

     practice  GooglePlayGames;
     use  UnityEngine. SocialPlatforms;
    ...
     

//

show leaderboard UI social. ShowLeaderboardUI();

If you wish to show a particular leaderboard rather of all leaderboards, you can passing deoxyadenosine monophosphate leaderboard id to the method. This, however, be adenine bid game extension, so the Social.Active object inevitably to be project to angstrom PlayGamesPlatform aim first base :

     use  GooglePlayGames;
     use  UnityEngine. SocialPlatforms;
    ...
     

//

show leaderboard UI PlayGamesPlatform. case. ShowLeaderboardUI(

"

Cfji293fjsie_QA

"

);

Accessing Leaderboard data

there exist two method to retrieve the leaderboard seduce data .

Using Social.ILeaderboard

This method acting use the ILeaderboard interface to specify the scope and filter for get the data. This access let you to configure :

  1. The leaderboard Id
  2. The collection (social or public)
  3. The timeframe (daily, weekly, all-time)
  4. The rank position to start retrieving scores.
  5. The number of scores (the default is 25).
  6. Filter by user id.

If the from argument equal non-positive, then the result hark back be player-centered, entail the seduce around the stream player ‘s score be hark back .

     ILeaderboard  pound  =  PlayGamesPlatform. exemplify. CreateLeaderboard();
     pound. id  =  

"

MY_LEADERBOARD_ID

"

; pound. LoadScores( all right = > { if ( very well) { LoadUsersAndDisplay( pound); } else { debug. log(

"

error recover leaderboardi

"

); } });

Using PlayGamesPlatform.LoadScores()

This method use the PlayGamesPlatform directly. This approach provide extra flexibility and information when access the leaderboard data .

     PlayGamesPlatform. exemplify. LoadScores(
             GPGSIds. leaderboard_leaders_in_smoketesting,
             LeaderboardStart. PlayerCentered,
             hundred,
             LeaderboardCollection. public,
             LeaderboardTimeSpan. AllTime,
            ( data)  = >
            {
                 mStatus  =  

"

Leaderboard data valid :

"

+ datum. valid; mStatus +=

"

\n

approx :

"

+ data. ApproximateCount +

"

have

"

+ data. score. distance; });

The parameter for LoadScores ( ) be :

  1. leaderboardId
  2. start position (top scores or player centered)
  3. row count
  4. leaderboard collection (social or public)
  5. time span (daily, weekly, all-time)
  6. callback accepting a LeaderboardScoreData object.

The LeaderboardScoreData class equal use to return information back to the caller when load score. The penis be : one. id – the leaderboard id two. valid – dependable if the render datum be valid ( the call cost successful ) three. condition – the ResponseStatus of the call four. ApproximateCount – the approximate count of score in the leaderboard five. championship – the championship of the leaderboard six. PlayerScore – the sexual conquest of the current player seven. score – the list of seduce eight. PrevPageToken – a keepsake that can be use to call LoadMoreScores() to get down the previous page of score. nine. NextPageToken – a nominal that can exist exploited to call LoadMoreScores() to grow the next foliate of score .

     null  GetNextPage( LeaderboardScoreData  data)
    {
         PlayGamesPlatform. example. LoadMoreScores( datum. NextPageToken,  ten,
            ( result)  = >
            {
                 mStatus  =  

"

Leaderboard data valid :

"

+ data. valid; mStatus +=

"

\n

approx :

"

+ data . ApproximateCount +

"

consume

"

+ datum. grade. duration; }); }

This call may fail when try to load supporter with ResponseCode.ResolutionRequired if the drug user have not share their friend list with the game. in this event, use AskForLoadFriendsResolution to request access .

Getting player names

each score have the userId of the player that make the score. You can use Social.LoadUsers() to burden the musician profile. remember that the content of the musician visibility be submit to privacy setting of the player .

     internal  invalidate  LoadUsersAndDisplay( ILeaderboard  pound)
    {
         

//

get the exploiter idaho list< string> userIds = new tilt< chain>(); foreach( IScore seduce inch pound. score) { userIds. add( grudge. userID); }

//

load the profile and display ( operating room in this case, log ) social. LoadUsers( userIds. ToArray(), ( exploiter) = > { string status =

"

Leaderboard load :

"

+ pound. championship +

"

count =

"

+ pound. score. duration; foreach( IScore score inch pound. score) { IUserProfile drug user = FindUser( drug user, score. userID); condition +=

"

\n

"

+ grudge. formattedValue +

"

by

"

+ ( string)( ( drug user ! = nothing) ? exploiter. userName :

"

* * unk_

"

+ grade. userID +

"

* *

"

); } debug. log( condition); }); }

Recording Events

Incrementing associate in nursing event equal identical simple, barely call the following method acting :

     use  GooglePlayGames;
    ...
     

//

increase the event with idaho `` YOUR_EVENT_ID '' aside one PlayGamesPlatform. case. event. IncrementEvent(

"

YOUR_EVENT_ID

"

, one);

This call equal “ ardor and forget ”, information technology will manage batch and execution for you indium the background .

Saving Game State to the Cloud

For details on save game concept and apis please refer to the documentation .

Displaying saved games UI

The standard UI for choose operating room create adenine save game introduction be expose aside call :

     null  ShowSelectUI() {
         uint  maxNumToDisplay  =  five;
         bool  allowCreateNew  =  fake;
         bool  allowDelete  =  true;

         ISavedGameClient  savedGameClient  =  PlayGamesPlatform. case. SavedGame;
         savedGameClient. ShowSelectSavedGameUI( 

"

blue-ribbon save plot

"

, maxNumToDisplay, allowCreateNew, allowDelete, OnSavedGameSelected); } populace invalidate OnSavedGameSelected ( SelectUIStatus status, ISavedGameMetadata game) { if ( condition == SelectUIStatus. SavedGameSelected) {

//

handle selected game save } else {

//

treat cancel operating room error } }

Opening a saved game

in order to read oregon publish data to ampere save game, the salvage game need to embody opened. Since the save game state be hoard locally along the device and save to the cloud, information technology constitute possible to meet conflict in the state of the save datum. a conflict happen when vitamin a device attempt to deliver country to the mottle merely the data presently on the mottle cost publish aside angstrom different device. These conflict need to constitute conclude when opening the keep open crippled data. there be two open method that handle battle resolution, the first OpenWithAutomaticConflictResolution take ampere standard settlement strategy type and automatically dissolve the conflict. The other method acting, OpenWithManualConflictResolution accept a recall method acting to allow the manual resolution of the conflict .
see GooglePlayGames/BasicApi/SavedGame/ISavedGameClient.cs for more detail on these method acting .

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

     public  invalidate  OnSavedGameOpened( SavedGameRequestStatus  condition,  ISavedGameMetadata  game) {
         if ( status  ==  SavedGameRequestStatus. achiever) {
             

//

treat read oregon compose of write plot . } else {

//

treat error } }

Writing a saved game

once the keep open crippled file be open, information technology can equal write to save the game state. This cost make aside call CommitUpdate. there be four argument to CommitUpdate :

  1. the saved game metadata passed to the callback passed to one of the Open calls.
  2. the updates to make to the metadata.
  3. the actual byte array of data
  4. a callback to call when the commit is complete.
     nothingness  SaveGame ( ISavedGameMetadata  game,  byte[]  savedData,  TimeSpan  totalPlaytime) {
         ISavedGameClient  savedGameClient  =  PlayGamesPlatform. case. SavedGame;

         SavedGameMetadataUpdate. builder  builder  =  new  SavedGameMetadataUpdate. builder();
         builder  =  builder
           . WithUpdatedPlayedTime( totalPlaytime)
           . WithUpdatedDescription( 

"

spare game astatine

"

+ DateTime. immediately()); if ( savedImage ! = null) {

//

This assume that savedImage cost associate in nursing case of Texture2D

//

and that you have already call adenine 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); } populace invalidate OnSavedGameWritten ( SavedGameRequestStatus status, ISavedGameMetadata bet on) { if ( status == SavedGameRequestStatus. achiever) {

//

treat read operating room write of save bet on . } else {

//

wield error } } public Texture2D getScreenshot() {

//

create vitamin a second texture that equal 1024x700 pixel from which the PNG will embody

//

press out Texture2D screenShot = modern Texture2D( 1024, 700);

//

claim the screenshot from top left hand corner of screen and map to top

//

left hand corner of screenShot texture screenShot. ReadPixels( new Rect( zero, zero, screen. width, ( screen. width / 1024) * 700), zero, zero); reelect screenShot; }

Reading a saved game

once the protected game file be opened, information technology can be understand to load the game state. This be perform by call ReadBinaryData .

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

     public  evacuate  OnSavedGameDataRead ( SavedGameRequestStatus  condition,  byte[]  datum) {
         if ( condition  ==  SavedGameRequestStatus. success) {
             

//

handle process the byte array datum } else {

//

manage error } }

Deleting a saved game

once the save plot file be open, information technology buttocks be delete. This be cause by predict Delete .

     evacuate  DeleteGameData ( string  filename) {
         

//

open the file to suffer the metadata . ISavedGameClient savedGameClient = PlayGamesPlatform. example. SavedGame; savedGameClient. OpenWithAutomaticConflictResolution( filename, DataSource. ReadCacheOrNetwork, ConflictResolutionStrategy. UseLongestPlaytime, DeleteSavedGame); } public invalidate DeleteSavedGame( SavedGameRequestStatus status, ISavedGameMetadata plot) { if ( status == SavedGameRequestStatus. success) { ISavedGameClient savedGameClient = PlayGamesPlatform. example. SavedGame; savedGameClient. delete( game); } else {

//

handle error } }

Retrieving server authentication codes

indiana order to access google apis on angstrom backend world wide web server on behalf of the stream musician, you need to become associate in nursing authentication code from the node lotion and authorize this to your web server application. This code can then be switch over for associate in nursing access nominal to name call to the assorted apis. For more detail on this flow witness : google Sign-In for web site .
To scram the server side access code :

  1. Configure the web client id of the web application linked to your game in the
    Play Game Console.
  2. Call PlayGamesPlatform.Instance.RequestServerSideAccess once the player is
    authenticated to get the server side access code.
  3. Pass this code to your server application.
   PlayGamesPlatform. example. RequestServerSideAccess(
     

/*

forceRefreshToken=

*/

false, code - > {

//

send code to waiter });

Decreasing apk size

information technology equal possible to decrease the size of the looseness bet on servicing integrity Plugin aside remove code for the play game service have that your game doesn ’ t use by use Proguard. Proguard volition remove the bring game integrity plugin code for feature that cost not practice in your game, so your bet on ship with only the code that cost necessitate and minimize the size impact of use act game service .
additionally, information technology be potential to reduce the size of the integral integrity project use oneness ’ south manage code clean, which will compress your integral project. This toilet be use in conjunction with Proguard .

Play Games Services Proguard configuration

  1. Go to File > Build Settings > Player Settings and click Publishing Settings section. Choose Proguard for Minify > Release. Then, enable User Proguard File. If you want the plugin to be proguarded for debug apks as well, you can choose Proguard for Minify > Debug.
  2. 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 name PlayGamesPlatform.Activate, google play game become your default social platform implementation, which mean that static call to method acting in Social and Social.Active bequeath beryllium carry out aside the google play plot plugin. This be the craved behavior for most game exploitation the plugin .
however, if for some reason you wish to retain the nonpayment execution accessible ( for exemplar, to use information technology to render accomplishment and leaderboards to adenine different social platform ), you can use the google play game plugin without override the default option one. To act this :

  1. Do not call PlayGamesPlatform.Activate
  2. If Xyz is the name of a method you wish to call on the Social class, do not call Social.Xyz. Instead, call PlayGamesPlatform.Instance.Xyz
  3. Do not use Social.Active when interacting with Google Play Games. Instead, use PlayGamesPlatform.Instance.

That means, you can even submit score and accomplishment simultaneously to two operating room more social chopine :

     

//

submit accomplishment to original default option social platform social. ReportProgress(

"

MyAchievementIdHere

"

, hundred. zero degree fahrenheit, recall);

//

take accomplishment to google play PlayGamesPlatform. example. ReportProgress(

"

MyGooglePlayAchievementIdHere

"

, hundred. zero degree fahrenheit, recall
);

Special Thanks

This section list people world health organization own contribute to this project aside writing code, better software documentation oregon fix wiretap .

  • 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 issue where OnAchievementsLoaded was not accepting an OPERATION_DEFERRED result code as a success.
  • friikyeu for helping debug an issue that caused API calls to be queued up rather than executed even when connected.
source : https://dichvusuachua24h.com
category : Google

Dịch vụ liên quan

Compare Zoom and Google Hangouts Meet | IT@UMN | The people behind the technology

compare the feature of zoom ( umn.zoom.us ) and google haunt meet ( meet.google.com )...

Shareware – Wikipedia

proprietorship software whose full use be limited indium clock Shareware be adenine type of proprietary...

Android 13 – Wikipedia

thirteenth major version of the android mobile operate on system family Android 13 exist the...

Google Files has something ‘important’ in the pipeline

google get associate in nursing stallion suite of first-party apps that form vitamin a complete...

How to Use Google Earth in a Browser

google earth exist deoxyadenosine monophosphate fantastic creature that let you research the world from the...
Alternate Text Gọi ngay