GitHub - Google Play Games Plugin For Unity

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 22

Google Play Games plugin for Unity

Copyright (c) 2014 Google Inc. All rights reserved.

Google Play mängude pistikprogramm Unity® jaoks on avatud lähtekoodiga projekt,


mille eesmärk on pakkuda pistikprogrammi, mis võimaldab mänguarendajatel
integreerida Unity®-s kirjutatud mängu Google Play mängude API-ga. Kuid Unity
Technologies ei toeta seda projekti mingil viisil ega kontrolli.

Unity® is a trademark of Unity Technologies.

iOS is a trademark of Apple, Inc.

Overview
Google Play mängude pistikprogramm Unity jaoks võimaldab teil pääseda juurde
Google Play mängude API-le Unity sotsiaalse liidese kaudu. Pistikprogramm toetab
järgmisi Google Play mängude API funktsioone:

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

See pistikprogrammi versioon ei toeta enam iOS-i. Google Play mänguteenused


iOS-ile on aegunud ja tõenäoliselt ei tööta ootuspäraselt. Ärge kasutage uutes
rakendustes iOS-i Google Play mänguteenuseid. Lisateabe saamiseks vaadake
ajaveebi postitust katkestamisteate kohta.

Funktsioonid:

• lihtne GUI-le orienteeritud projekti seadistamine (integreeritud Unity GUI-sse)

• pole vaja pleieri tegevust (player Activity) alistada/kohandada (override/customize)

• pole vaja AndroidManifest.xml alistada/kohandada

System requirements:

 Unity® 2017.4 or above.


 To deploy on Android:

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

Uuendamine
Kui olete juba integreerinud oma projekti pistikprogrammi eelmise versiooniga ja
soovite minna üle uuele versioonile, vaadake versiooniuuenduse juhiseid upgrade
instructions

Seadistage oma mäng


Pistikprogrammi kasutamiseks peate esmalt oma mängu Google Play
arendajakonsoolis konfigureerima configure your game. Järgige kliendi ID loomise
juhiseid. Olge paketi nime ja sertifikaadi sõrmejälgede sisestamisel eriti ettevaatlik,
kuna nendel ekraanidel esinevaid vigu võib olla raske taastada.

Copy the game resources from the console


Kui olete konfigureerinud vähemalt ühe ressursi (sündmuse, saavutuse või edetabeli),
kopeerige ressursi konfiguratsioon Google Play arendajakonsoolist ja kleepige see
Unity seadistuskonfiguratsiooni. Ressursside hankimiseks minge vahekaardile
Saavutused, seejärel klõpsake loendi allosas nuppu " Get resources ".

Then click the "Android section".


Valige kogu ressursside akna sisu ja kopeerige need lõikepuhvrisse.

Kleepige mänguressursid pistikprogrammi seadistamise


dialoogi
Tagasi Unity'is avage häälestusdialoog Window > Google Play Games > Setup... >
Android Setup
• Enter the directory to save constants - sisestage konstantide faili kaust.

• Constants class name – see on loodava C# klassi nimi, sealhulgas nimeruum.

• Resources Definition – kleepige siia Play mängude konsooli ressursiandmed.

• Web client ID – see on lingitud veebirakenduse kliendi ID. Seda on vaja ainult siis,
kui teil on oma mängu jaoks veebipõhine taustaprogramm ja vajate serveri
autentimiskoodi, mille taustaserver vahetab juurdepääsuloa vastu, või kui teil on vaja
ID-luba, et mängija saaks teha muud, mittemängu (non-game) , API kõned.

Seadistusprotsess konfigureerib teie mängu kliendi ID-ga ja genereerib C#-klassi, mis


sisaldab iga teie ressursi jaoks konstante.

Seadistamise kontrollloend Checklist


Kui need on teie mängu jaoks asjakohased, tehke kindlasti järgmist.
1. Lisage testijate e-posti aadressid Play mängukonsooli mängu testimise jaotisesse.
2. Lingitud Androidi rakenduse loomiseks kasutatav SHA1 sõrmejälg pärineb Unity rakenduse
allkirjastamiseks kasutatavast võtmehoidlast.

Lisage saavutusi ja edetabeleid (Add Achievements


and Leaderboards)
Lisage Google Play arendajakonsoolis oma mängu saavutusi ja edetabeleid
(achievements and leaderboards). Märkige kindlasti iga konfigureeritud saavutuse ja
edetabeli puhul vastav achievement ID või leaderboard ID, kuna neid läheb vaja
API-kõnede tegemisel. Saavutuste ja edetabeli ID-d on tähtnumbrilised stringid (nt
"Cgkx9eiuwi8_AQ").

Add Events
Sündmused võimaldavad teil jälgida kasutajate toiminguid teie mängus ja koostada
nende kohta Analyticsi abil aruandeid. Lisateavet sündmuste konfigureerimise ja
kasutamise kohta leiate jaotisest Game Concepts - Events

Load Your Game Project


Järgmisena laadige oma mänguprojekt Unity redaktorisse.
Kui teil pole mänguprojekti, millega töötada, võite kasutada näidiste kataloogis
saadaolevat minimaalset (Minimal) näidist. Selle näidise kasutamine võimaldab teil
oma seadistust kiiresti testida ja veenduda, et pääsete API-le juurde.

Kui soovite pärast pistikprogrammiga tutvumist testida suuremat proovi, proovige


mängu CubicPilot. Lisateavet näidiste ehitamise kohta leiate näidiste README failist
samples README.

Plugin Installation
Plugina allalaadimiseks kloonige see Giti hoidla oma failisüsteemi (või laadige see
ZIP-failina alla ja pakkige lahti). Seejärel otsige praeguse ehituse kataloogist üles
unitypackage'i fail:

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

Pistikprogrammi installimiseks avage lihtsalt oma mänguprojekt Unity'is ja importige


see fail oma projekti varadesse, nagu teeksite seda iga teise Unity paketi puhul. Seda
saab teha menüükäsuga Assets > Import Package > Custom Package (sellesse
menüüsse pääsete ka kaustal Assets paremklõpsates).

Järgmiseks veenduge, et teie praegune ehitusplatvorm on seadistatud Androidile.


Valige menüüst File > Build Settings… valige Android ja klikake Switch Platform.
Nüüd peaksite nägema, et jaotises Window > Google Play Games mängud lisati uus
menüüelement. Kui te uusi menüüüksusi ei näe, värskendage varasid, klõpsates
valikutel Assets > Refresh ja proovige uuesti.

Android Setup
Järgmisena seadistage Unity'is oma Android SDK installimise tee. See asub eelistuste
(preferences) menüüs jaotises External Tools.

Unity mängu konfigureerimiseks Androidis Google Play mängudega käitamiseks


avage esmalt Androidi SDK haldur ja kontrollige, kas olete alla laadinud järgmised
paketid. Sõltuvalt sellest, kas kasutate Android Studio SDK-haldurit või eraldiseisvat
SDK-haldurit, võivad komponentide nimed erineda.

 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).
Järgmisena konfigureerige oma mängu paketi nimi. Selleks klõpsake nuppu File >
Build Settings, valige Androidi platvorm ja klõpsake Unity Playeri seadete akna
kuvamiseks nuppu Player Settings. Selles aknas otsige jaotisest Other Settings sätet
Bundle Identifier. Sisestage sinna oma paketi nimi (näiteks
com.example.my.awesome.game).

Play mänguteenustesse sisselogimiseks peate allkirjastama oma APK-faili ja


veenduma, et allkirjastate selle õige sertifikaadiga, st sellega, mis vastab SHA1
sertifikaadi sõrmejäljele, mille sisestasite arendajakonsooli seadistamisel.

Järgmisena klõpsake menüü üksusel Window |Google Play Games|Setup - Android


setup. See kuvab Androidi seadistuskuva.

Sisestage konstantide klassi nimi. See on täielikult kvalifitseeritud klassi nimi, mida
värskendatakse (või luuakse), mis sisaldab mänguressursside ID-sid. Nime vorming on
.. Näiteks AwesomeGame.GPGSIds

Kleepige ressursi määratluse andmed (resource definition data). Need on Google Play
arendajakonsooli XML-andmed, mis sisaldavad nii ressursi ID-sid kui ka Androidi
rakenduse ID-d.

Need andmed leiate Google Play arendajakonsoolist, klõpsates mis tahes ressursilehe
(nt saavutused või edetabelid) valikul „Hangi ressursse” ja seejärel klõpsates Androidil.

Pärast andmete tekstialale kleepimist klõpsake nuppu Setup.

Märkus. Kui kasutate oma mänguga veebirakendust või taustaserverit, saate


veebirakenduse mänguga linkida, et võimaldada mängija ID-märgi ja/või e-posti
aadressi hankimist. Selleks linkige veebirakendus Google Play arendajakonsoolis
mänguga ja sisestage häälestusdialoogi veebirakenduse kliendi ID.

Täiendavad juhised Androidi loomiseks Windowsis


Kui kasutate Windowsi, peate veenduma, et Unity pääseb teie Java SDK installile
juurde. Selleks tehke järgmist.

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 Windows 2000/XP/Vista/7, right-click My


Computer, then Properties, then go to Advanced System Properties (or System
Properties and then click the Advanced tab), then click Environment Variables. On
Windows 8, press Windows Key + W and search for environment variables For
more information, consult the documentation for your version of Windows.

Käivitage projekt
Kui töötate Smoketest näidisega, peaksite saama projekti praegusel hetkel koostada
ja käivitada. Kui Smoketest käivitub, näete automaatset sisselogimiskatset.

Androidi loomiseks ja käitamiseks klõpsake nuppu File > Build Settings, select
the Android platform, then Switch to Platform, then Build and Run.

ISocialPlatform Compliance
The Google Play Games plugin implements Unity's 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 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 class, where the additional methods are available.

Nearby Connections Configuration


Lähedal asuvate ühenduste kasutamiseks tuleb konfigureerida teenuse ID, mis
tuvastab unikaalselt interakteeruvate rakenduste komplekti. Selleks klõpsake
menüükäsku Window > Google Play Games > Nearby Connections setup... . See
kuvab lähedalasuvate ühenduste seadistamise ekraani. Sisestage sellel ekraanil
teenuse ID, mida soovite kasutada. See peaks olema midagi, mis tuvastab teie
rakenduse ja järgib samu reegleid kui kogumi ID (näiteks:

com.example.myawesomegame.nearby). Kui olete ID sisestanud, vajutage Setup.

Lähedal asuvate ühenduste kasutamiseks ei pea mängija autentima ja Google Play


arendajakonsooli konfiguratsiooni pole vaja.

Läheduses asuvate ühenduste kasutamise kohta üksikasjaliku teabe saamiseks


vaadake lähedalasuvaid ühendusi nearby connections.

Sign in
Mängu avamisel luuakse automaatselt ühendus mänguteenustega. Kui ühendus on
edukas, tervitatakse mängijat hüpikaknaga ja teie mäng on valmis Games Unity
pluginat kasutama.

Märkus. Kui kasutaja pole selles seadmes kunagi Google Play mänge kasutanud,
viiakse ta automaatselt läbi ühekordsete seadistustoimingute, näiteks Play mängude
rakendusega profiili loomise.

Kuulake oma skripti meetodis Start automaatse sisselogimiskatse tulemust, hankige


autentimise olek ja keelake Play mänguteenuste funktsioonid, kui kasutaja pole sisse
logitud.
using GooglePlayGames;

public void Start() {


PlayGamesPlatform.Instance.Authenticate(ProcessAuthentication);
}

internal void ProcessAuthentication(SignInStatus status) {


if (status == SignInStatus.Success) {
// Continue 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 call
//
PlayGamesPlatform.Instance.ManuallyAuthenticate(ProcessAuthentication).
}
}
}

The result code is an enum, which gives you different failure reasons that will help
you understand 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 Start() {


PlayGamesPlatform.Activate();
Social.localUser.Authenticate(ProcessAuthentication);
}

Pange tähele, et te ei saa teha mängude API-kõnesid (saavutuste avamine, tulemuste


postitamine jne unlock achievements, post scores, etc) enne, kui olete saanud
autentimiselt eduka tagastusväärtuse, seega on hea tava panna ooterežiimi ekraan
kuni tagasihelistamiseni, et veenduda, et kasutaja ei saa mängu alustada enne, kui
autentimisprotsess on lõppenud.

Friends
Play Games Friends allows players to create and maintain a cross-games friends list.
You can request access to this friends list 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 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.

See the best practices guidelines for instructions on how best to implement these
APIs.

Note: To use Friends, you need to update your PGS SDK to version 20.0.0

View friends
There 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 call will fail if the current player has not yet granted permission to the
game to access this information. Use GetLastLoadFriendsStatus to check
if LoadFriends failed due to missing consent.
PlayGamesPlatform.Instance.GetLastLoadFriendsStatus((status) => {
// Check for consent
if (status == LoadFriendsStatus.ResolutionRequired) {
// Ask for resolution.
}
});

A game can ask the current player to share the friends list by
calling AskForLoadFriendsResolution.
PlayGamesPlatform.Instance.AskForLoadFriendsResolution((result) => {
if (result == UIStatus.Valid) {
// User agreed to share friends with the game. Reload friends.
} else {
// User doesn’t agree to share the friends list.
}
});
This function will show the appropriate 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 way 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.Instance.LoadMoreFriends(pageSize, (status) => {


// 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 contain 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 true, this call will clear any locally-cached
data and attempt to fetch the latest data from the server. This would commonly be
used for actions like a user-initiated refresh. Normally, this should be set to false to
gain the advantages of data caching.
If the callback returns LoadFriendsStatus.LoadMore, then there are more friends to
load. LoadFriendsStatus.ResolutionRequired signals that the user has not shared
the friends list and you can directly
call PlayGamesPlatform.Instance.AskForLoadFriendsResolution.

Determining friends list visibility

Use PlayGamesPlatform.Instance.GetFriendsListVisibility to check if the user


has shared the friends list with the game. Possible return statuses 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.Instance.GetFriendsListVisibility(forceReload,
(friendsListVisibilityStatus) => {});

View a player profile


To add or remove a player as a friend, use the show and compare profile function.
This function triggers a bottom sheet dialog showing the Play Games profile of the
user; call the function with the player Id of the requested player. If the player and
friend have in-game nicknames, use them in the call to add more context to the
profile UI:
PlayGamesPlatform.Instance.ShowCompareProfileWithAlternativeNameHintsUI(
mFirstFriendId, /* otherPlayerInGameName= */ null, /*
currentPlayerInGameName= */ null,
(result) => {
// Profile comparison view has closed.
});

Player Statistics
Mängijastatistika API (The Player Stats API) võimaldab teil kohandada
mängukogemusi vastavalt mängijate konkreetsetele segmentidele ja mängija
elutsükli erinevatele etappidele. Saate luua iga mängijasegmendi jaoks kohandatud
kogemusi vastavalt mängijate edenemisele, kulutamisele ja kaasamisele. Näiteks saate
seda API-t kasutada ennetavate toimingute tegemiseks, et julgustada vähem aktiivset
mängijat teie mänguga uuesti tegelema, näiteks kuvades ja reklaamides uusi
mängusiseseid üksusi, kui mängija sisse logib.

Tagasihelistamisel on kaks parameetrit:

1. Tulemuskood, mis on väiksem või võrdne nulliga, on edukas. Kõikide väärtuste


jaoks vaadake jaotist CommonStatusCodes.

2. Objekti PlayerStats tüüp GooglePlayGames.PlayGamesLocalUser.PlayerStats

Lisateabe saamiseks vaadake Mängija statistika Player Stats.

Mängija statistika on saadaval pärast autentimist:


((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 Achievement
To unlock an achievement, use the Social.ReportProgress method with a progress
value of 100.0f:
using GooglePlayGames;
using UnityEngine.SocialPlatforms;
...
// unlock achievement (achievement ID "Cfjewijawiu_QA")
Social.ReportProgress("Cfjewijawiu_QA", 100.0f, (bool success) => {
// handle success or failure
});

Notice that according to the expected behavior of Social.ReportProgress, a progress


of 0.0f means 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
behavior according to Unity's social API, but may not be exact. For this reason, we
recommend that you 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;
...
// increment achievement (achievement ID "Cfjewijawiu_QA") by 5 steps
PlayGamesPlatform.Instance.IncrementAchievement(
"Cfjewijawiu_QA", 5, (bool success) => {
// handle success or failure
});

Tulemuste postitamine edetabelisse (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 use the Play Game Services instance
directly:
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
});
Pange tähele, et platvorm ja server jätavad mängija olemasolevast rekordist
madalamad punktisummad automaatselt kõrvale, nii et saate hindeid vabalt esitada
ilma igasuguste kontrollideta, et kontrollida, kas skoor on mängija olemasolevast
punktisummast suurem või mitte.

Saavutuste kasutajaliidese kuvamine (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 built-in UI for all leaderboards, call Social.ShowLeaderboardUI.
using GooglePlayGames;
using UnityEngine.SocialPlatforms;
...
// show leaderboard UI
Social.ShowLeaderboardUI();

If you wish to show a particular leaderboard instead of all leaderboards, you can pass
a leaderboard ID to the method. This, however, is a Play Games extension, so the
Social.Active object needs to be cast to a PlayGamesPlatform object first:
using GooglePlayGames;
using UnityEngine.SocialPlatforms;
...
// show leaderboard UI
PlayGamesPlatform.Instance.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 scope and filters for
getting the data. This approach allows 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 parameter is non-positive, then the results returned are player-centered,
meaning the scores around the 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 information 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 + " have " +
data.Scores.Length;
});

The parameters for LoadScores() are:

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 is used to return information 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.
Title - the title of the leaderboard 6. PlayerScore - the score of the current player 7.
Scores - the list of scores 8. PrevPageToken - a token that can be used to
call LoadMoreScores() to get the previous page of scores. 9. NextPageToken - a token
that can be used to call LoadMoreScores() to get the next page of scores.
void GetNextPage(LeaderboardScoreData data)
{
PlayGamesPlatform.Instance.LoadMoreScores(data.NextPageToken, 10,
(results) =>
{
mStatus = "Leaderboard data valid: " + data.Valid;
mStatus += "\n approx:" +data.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 case, use AskForLoadFriendsResolution to request access.

Getting player names


Each score has the userId of the player that made the score. You can
use Social.LoadUsers() to load the player profile. Remember that the contents of
the player profile are subject to privacy settings of the players.
internal void LoadUsersAndDisplay(ILeaderboard lb)
{
// get the user ids
List<string> userIds = new List<string>();

foreach(IScore score in lb.scores) {


userIds.Add(score.userID);
}
// load the profiles and display (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);
status += "\n" + score.formattedValue + " by " +
(string)(
(user != null) ? 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 event 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 in the
background.

Saving Game State to the Cloud


For details on saved games concepts and APIs please 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 cancel 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, it
is possible to encounter conflicts in the state of the saved data. A conflict happens
when a device attempts to save state to the cloud 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 2 open methods that handle conflict resolution, the
first 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 conflict.

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, it can be written to save the game state. This is
done by calling CommitUpdate. There are four parameters 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.

void SaveGame (ISavedGameMetadata game, byte[] savedData, TimeSpan


totalPlaytime) {
ISavedGameClient savedGameClient =
PlayGamesPlatform.Instance.SavedGame;

SavedGameMetadataUpdate.Builder builder = new


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

public void OnSavedGameWritten (SavedGameRequestStatus status,


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

public Texture2D getScreenshot() {


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

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

Reading a saved game


Once the saved game file is opened, it 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[]


data) {
if (status == SavedGameRequestStatus.Success) {
// handle processing the byte array data
} else {
// handle error
}
}

Deleting a saved game


Once the saved game file is opened, it can be deleted. This is done by calling Delete.
void DeleteGameData (string filename) {
// Open the file to get the metadata.
ISavedGameClient savedGameClient =
PlayGamesPlatform.Instance.SavedGame;
savedGameClient.OpenWithAutomaticConflictResolution(filename,
DataSource.ReadCacheOrNetwork,
ConflictResolutionStrategy.UseLongestPlaytime,
DeleteSavedGame);
}

public void DeleteSavedGame(SavedGameRequestStatus status,


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

Retrieving server authentication codes


In order to access Google APIs on a backend web server on behalf of the current
player, you need to get an authentication code from the client application and pass
this to your web server application. This code can then be exchanged for an access
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 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.Instance.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 by
removing code for the Play Games Services features that your game doesn’t use 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 only the code that is needed
and minimizes the size impact of using Play Games Services.

Additionally, it is possible to reduce the size of the entire Unity project using
Unity’s Managed Code Stripping, which will compress your entire project. This can be
used 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 call PlayGamesPlatform.Activate, Google Play Games becomes your
default social platform implementation, which means that static calls to methods
in Social and Social.Active will be carried out by the Google Play Games plugin.
This is the desired behavior for most games using the plugin.
However, if for some reason you wish to keep the default implementation accessible
(for example, 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:

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 way, you can even submit scores and achievements simultaneously to two or
more social platforms:
// Submit achievement to original default social platform
Social.ReportProgress("MyAchievementIdHere", 100.0f, callback);

// Submit achievement to Google Play

PlayGamesPlatform.Instance.ReportProgress("MyGooglePlayAchievementIdHere",
100.0f, callback);

Special Thanks
This section lists people who have contributed to this project by 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 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.

You might also like