Game Services: Scripting

This section provides a guide to work with the Game Services module scripting API.

You can access the Game Services module API via the GameServices class under the EasyMobile namespace.

Initialization

Initialization is required before any other action, e.g. reporting scores, can be done. It should only be done once when the app is loaded. If you have enabled the Auto initialization feature, you don't need to initialize in script (see Auto Initialization section). Otherwise, if you choose to disable that feature, you can start the initialization in a couple of ways.

  • Managed initialization: this method respects the Max Login Requests value on Android (see Auto Initialization section), which means it will ignore all subsequent calls once the user has dismissed the login popup for a number of time determined by Max Login Requests
  • Unmanaged initialization: this method simply initializes the module, on Android it shows the login popup every time as long as the user hasn't been authenticated

On iOS, the system automatically limits the maximum number of login requests to 3 no matter which method is used.

To use the managed initialization method:

// Managed init respects the Max Login Requests value
GameServices.ManagedInit();

To use the unmanaged initialization method:

// Unmanaged init
GameServices.Init();

Note that the initialization should be done early and only once, e.g. you can put it in the Start method of a MonoBehaviour, preferably a singleton one so that it won't run again when the scene reloads.

// Initialization in the Start method of a MonoBehaviour script
void Start()
{
    // Managed init respects the Max Login Requests value
    GameServices.ManagedInit();   

    // Do other stuff...
}

A UserLoginSucceeded event will be fired when the initialization completes and the user logins successfully. Otherwise, a UserLoginFailed event will be fired instead. You can optionally subscribe to these events and take appropriate actions depended on the user login status.

// Subscribe to events in the OnEnable method of a MonoBehavior script
void OnEnable()
{
    GameServices.UserLoginSucceeded += OnUserLoginSucceeded;
    GameServices.UserLoginFailed += OnUserLoginFailed;
}

// Unsubscribe
void OnDisable()
{
    GameServices.UserLoginSucceeded -= OnUserLoginSucceeded;
    GameServices.UserLoginFailed -= OnUserLoginFailed;
}

// Event handlers
void OnUserLoginSucceeded()
{
    Debug.Log("User logged in successfully.");
}

void OnUserLoginFailed()
{
    Debug.Log("User login failed.");
}

You can also check if the module has been initialized at any point using the IsInitialized method.

// Check if initialization has completed (the user has been authenticated)
bool isInitialized = GameServices.IsInitialized();

Leaderboards

This section focuses on working with leaderboards.

Show Leaderboard UI

To show the default leaderboard UI (the system view of leaderboards):

// Show leaderboard UI
GameServices.ShowLeaderboardUI();

You should check if the initialization has finished (the user has been authenticated) before showing the leaderboard UI, and take appropriate actions if the user is not logged in, e.g. show an alert or start another initialization process.

// Check for initialization before showing leaderboard UI
if (GameServices.IsInitialized())
{
    GameServices.ShowLeaderboardUI();
}
else
{
    #if UNITY_ANDROID
    GameServices.Init();    // start a new initialization process
    #elif UNITY_IOS
    Debug.Log("Cannot show leaderboard UI: The user is not logged in to Game Center.");
    #endif
}

To show the UI of a specific leaderboard, simply pass the name of the leaderboard into the ShowLeaderboardUI method. You can also optionally specify the time scope:

// Show a specific leaderboard UI
GameServices.ShowLeaderboardUI("YOUR_LEADERBOARD_NAME");

// Show a specific leaderboard UI in the Week time scope
GameServices.ShowLeaderboardUI("YOUR_LEADERBOARD_NAME", TimeScope.Week);

Report Scores

To report scores to a leaderboard you need to specify the name of that leaderboard.

It is strongly recommended that you use the constants of leaderboard names in the generated EM_GameServicesConstants class (see Game Services Constants Generation section) instead of typing the names directly in order to prevent runtime errors due to typos and the likes.

// Report a score of 100
// EM_GameServicesConstants.Sample_Leaderboard is the generated name constant
// of a leaderboard named "Sample Leaderboard"
GameServices.ReportScore(100, EM_GameServicesConstants.Sample_Leaderboard);

Load Local User's Score

You can load the score of the local user (the authenticated user) on a leaderboard, to do so you need to specify the name of the leaderboard to load score from and a callback to be called when the score is loaded.

// Put this on top of the file to use IScore
UnityEngine.SocialPlatforms;



// Load the local user's score from the specified leaderboard
// EM_GameServicesConstants.Sample_Leaderboard is the generated name constant
// of a leaderboard named "Sample Leaderboard"
GameServices.LoadLocalUserScore(EM_GameServicesConstants.Sample_Leaderboard, OnLocalUserScoreLoaded);



// Score loaded callback
void OnLocalUserScoreLoaded(string leaderboardName, IScore score)
{
    if (score != null)
    {
        Debug.Log("Your score is: " + score.value);
    }
    else
    {
        Debug.Log("You don't have any score reported to leaderboard " + leaderboardName);
    }
}

Load Scores

You can load a set of scores from a leaderboard with which you can specify the start position to load score, the number of scores to load, as well as the time scope and user scope.

// Put this on top of the file to use IScore
UnityEngine.SocialPlatforms;



// Load a set of 20 scores starting from rank 10 in Today time scope and Global user scope
// EM_GameServicesConstants.Sample_Leaderboard is the generated name constant
// of a leaderboard named "Sample Leaderboard"
GameServices.LoadScores(
    EM_GameServicesConstants.Sample_Leaderboard,
    10,
    20,
    TimeScope.Today,
    UserScope.Global,
    OnScoresLoaded
);



// Scores loaded callback
void OnScoresLoaded(string leaderboardName, IScore[] scores)
{
    if (scores != null && scores.Length > 0)
    {
        Debug.Log("Loaded " + scores.Length + " from leadeboard " + leaderboardName);
        foreach (IScore score in scores)
        {
            Debug.Log("Score: " + score.value + "; rank: " + score.rank);
        }
    }
    else
    {
        Debug.Log("No score loaded.");
    }
}

You can also load the default set of scores, which contains 25 scores around the local user's score in the AllTime time scope and Global user scope.

// Put this on top of the file to use IScore
UnityEngine.SocialPlatforms;



// Load the default set of scores
// EM_GameServicesConstants.Sample_Leaderboard is the generated name constant
// of a leaderboard named "Sample Leaderboard"
GameServices.LoadScores(EM_GameServicesConstants.Sample_Leaderboard, OnScoresLoaded);



// Scores loaded callback
void OnScoresLoaded(string leaderboardName, IScore[] scores)
{
    if (scores != null && scores.Length > 0)
    {
        Debug.Log("Loaded " + scores.Length + " from leadeboard " + leaderboardName);
        foreach (IScore score in scores)
        {
            Debug.Log("Score: " + score.value + "; rank: " + score.rank);
        }
    }
    else
    {
        Debug.Log("No score loaded.");
    }
}

Get All Leaderboards

You can obtain an array of all leaderboards created in the module settings interface:

// Get the array of all leaderboards created in the Game Service module settings
// Leaderboard is the class representing a leaderboard as declared in the module settings
// The GameServices property of EM_Settings class holds the settings of this module
Leaderboard[] leaderboards = EM_Settings.GameServices.Leaderboards;

// Print all leaderboard names
foreach (Leaderboard ldb in leaderboards)
{
    Debug.Log("Leaderboard name: " + ldb.Name);
}

Achievements

This section focuses on working with achievements.

Show Achievement UI

To show the achievements UI (the system view of achievements):

// Show achievements UI
GameServices.ShowAchievementsUI();

You should check if the initialization has finished (the user has been authenticated) before showing the achievements UI, and take appropriate actions if the user is not logged in, e.g. show an alert or start another initialization process.

// Check for initialization before showing achievements UI
if (GameServices.IsInitialized())
{
    GameServices.ShowAchievementsUI();
}
else
{
    #if UNITY_ANDROID
    GameServices.Init();    // start a new initialization process
    #elif UNITY_IOS
    Debug.Log("Cannot show achievements UI: The user is not logged in to Game Center.");
    #endif
}

Reveal an Achievement

To reveal a hidden achievement, simply specify its name.

As in the case of leaderboards, it is strongly recommended that you use the constants of achievement names in the generated EM_GameServicesConstants class instead of typing the names directly.

// Reveal a hidden achievement
// EM_GameServicesConstants.Sample_Achievement is the generated name constant
// of an achievement named "Sample Achievement"
GameServices.RevealAchievement(EM_GameServicesConstants.Sample_Achievement);

Unlock an Achievement

To unlock an achievement:

// Unlock an achievement
// EM_GameServicesConstants.Sample_Achievement is the generated name constant
// of an achievement named "Sample Achievement"
GameServices.UnlockAchievement(EM_GameServicesConstants.Sample_Achievement);

Report Incremental Achievement's Progress

To report the progress of an incremental achievement:

// Report a rogress of 50% for an incremental achievement
// EM_GameServicesConstants.Sample_Incremental_Achievement is the generated name constant
// of an incremental achievement named "Sample Incremental Achievement"
GameServices.ReportAchievementProgress(EM_GameServicesConstants.Sample_Incremental_Achievement, 50.0f);

Get All Achievements

You can obtain an array of all achievements created in the module settings interface:

// Get the array of all achievements created in the Game Service module settings
// Achievement is the class representing an achievement as declared in the module settings
// The GameService property of EM_Settings class holds the settings of this module
Achievement[] achievements = EM_Settings.GameServices.Achievements;

// Print all achievement names
foreach (Achievement acm in achievements)
{
    Debug.Log("Achievement name: " + acm.Name);
}

User Profiles

You can load the profiles of friends of the local (authenticated) user. When the loading completes the provided callback will be invoked.

// Put this on top of the file to use IUserProfile
UnityEngine.SocialPlatforms;


// Load the local user's friend list
GameServices.LoadFriends(OnFriendsLoaded);


// Friends loaded callback
void OnFriendsLoaded(IUserProfile[] friends)
{
    if (friends.Length > 0)
    {
        foreach (IUserProfile user in friends)
        {
            Debug.Log("Friend's name: " + user.userName + "; ID: " + user.id);
        }
     }
     else
     {
         Debug.Log("Couldn't find any friend.");
     }
}

You can also load user profiles by providing their IDs.

// Put this on top of the file to use IUserProfile
UnityEngine.SocialPlatforms;


// Load the profiles of the users with provided IDs
// idArray is the (string) array of the IDs of the users to load profiles
GameServices.LoadUsers(idArray, OnUsersLoaded);


// Users loaded callback
void OnUsersLoaded(IUserProfile[] users)
{
    if (users.Length > 0)
    {
        foreach (IUserProfile user in users)
        {
            Debug.Log("User's name: " + user.userName + "; ID: " + user.id);
        }
     }
     else
     {
         Debug.Log("Couldn't find any user with the specified IDs.");
     }
}

Google Play Game Service now requires the user's consent before you're able to access any API that involves the user's friend list (e.g. friends only leaderboard, user profile). You can request for user's consent by following the below example. Note that this API is only available on Android.

//Request user's friend list access consent.
GameServices.AskForLoadFriendsResolution((status) =>
{
    //callback from the request
});

The possible result can be {Valid, Internal Error, Not Authorized, Version Update Required, Time out, User close UI, Ui busy, Network error, Not initialized}. Only the Valid result means the user has authorized the consent, the rest means something wrong happened and result in not authorized result.

Sign Out

To sign the user out, simply call the SignOut method. Note that this method is only effective on Android.

// Sign the user out on Android
GameServices.SignOut();

results matching ""

    No results matching ""