Implementing Feature

Now, you are ready to begin implementation of Game Services feature. Our cross-platform Game Services component provides a single interface/API to access Leaderboards and Achievements.

Use NPBinding.GameServices to access Game Services features from code.

Note: All the classes, datatypes related to the plugin are placed under namespace VoxelBusters.NativePlugins. Add this namespace in your script before accessing any of the features.

Make sure you save all your GLobal ID's (you set in NPSettings for Achievements and Leaderboards) so that you can refer them from code.


Check if Game Services is available

First thing, we need to do is to check if game services are supported on running platform. If available we can proceed with sign in.

bool _isAvailable = NPBinding.GameServices.IsAvailable();

This returns true if service is supported on the platform application is running, false otherwise.

If service is available, we can move on to sign in/Authenticate user.


Authenticate/Sign-In

User type can hold any player who is connected to Game Services.

  • User instance can hold Name, Identifier and Alias.
  • Use GetImageAsync method to download User's picture.

LocalUser is an User who logs-in on the device. This Class provides a single interface to do Authetication process.

You can access LocalUser Instance by :

NPBinding.GameServices.LocalUser
Authenticate / Sign-In Local User

Check if LocalUser is already logged in or not by below code snippet.

bool _isAuthenticated = NPBinding.GameServices.LocalUser.IsAuthenticated;

Above method returns true if player already signed in. Incase, if not, let him finish authenitcation by calling Authenticate method. This returns true if authentication process succeeds. Else a non-null error string.

//Authenticate Local User
NPBinding.GameServices.LocalUser.Authenticate((bool _success, string _error)=>{

                if (_success)
                {
                    Debug.Log("Sign-In Successfully");
                    Debug.Log("Local User Details : " + NPBinding.GameServices.LocalUser.ToString());
                }
                else
                {
                    Debug.Log("Sign-In Failed with error " + _error);
                }
            });
  • On iOS, Authenticate call shows up Game Center login view.

  • On Android, Authenticate call shows up Google Play Services login view.


Load Friends of Local User

Connected friends can be loaded by using LoadFriends method of LocalUser.

/Load Friends of Local User
NPBinding.GameServices.LocalUser.LoadFriends((User[] _friendsList, string _error) =>{
                if(_friendsList != null)
                {
                    Debug.Log("Succesfully loaded user friends.");
                    foreach(User _eachFriend in _friendsList)
                    {
                        Debug.Log(string.Format("Name : {0}, Id : {1}", _eachFriend.Name, _eachFriend.Identifier));
                    }
                }
                else
                {
                    Debug.Log("Failed to load user friends with error " + _error);
                }

            });

This method returns a list of User's and a non-empty error string, if any error happens.

Load any User Information

Fetch details of users from user identifier. You need to pass an array of identifiers for which you want to get the details.

//Load details of specific users
string[] _userIDList = new string{"ID_1", "ID_2"};
NPBinding.GameServices.LoadUsers(_userIDList, (User[] _users, string _error) =>{
                if(_users != null)
                {
                    Debug.Log("Succesfully loaded users info.");
                    foreach(User _eachUser in _users)
                    {
                        Debug.Log(string.Format("Name : {0}, Id : {1}", _eachUser.Name, _eachUser.Identifier));
                    }
                }
                else
                {
                    Debug.Log("Failed to load users info with  error = " + _error);
                }

            });

This method returns a list of User's requested and a non-empty error string, if any error happens.


Sign-Out from Game Services

If you want to sign out of current logged in account, use SignOut method of LocalUser instance.

NPBinding.GameServices.LocalUser.SignOut((bool _success, string _error)=>{

    if (_success)
    {
        Debug.Log("Local user is signed out successfully!");
    }
    else
    {
        Debug.Log("Request to signout local user failed.");
        Debug.Log(string.Format("Error= {0}.", _error.GetPrintableString()));
    }
});

Note : Android Platform

Its recommended to provide Sign Out option to user as per Google Guidelines.


Achievements

Lets have a look at the keywords used in this feature.

Achivement : Achievements can be a great way to increase your users' engagement within your game. Achievements can also be a fun way for players to compare their progress with each other and engage in light-hearted competition.

Achievement Description : This holds description and images used to describe an achievement. Some of them are :

  • Description
  • Image
  • IsHidden flag
  • Global Identifier

Achievement Progress : This denotes how much part of achivement is achieved.

  • 100 % progress denotes Achievement is Unlocked and revealed to the player.
  • One shot/Instant achievements unlock instantly and needs to be set 100% while reporting.
  • Incremental achievements (which takes many steps to get unlocked) can be set with 0-100% range.
Fetch Achievements

This fetches the achievments ONLY unlocked or revealed by the player till date.

NPBinding.GameServices.LoadAchievements((Achievement[] _achievements, string _error)=>{

                if (_achievements == null)
                {
                    Debug.Log("Couldn't load achievement list with error = " + _error);
                    return;
                }

                int        _achievementCount    = _achievements.Length;
                Debug.Log(string.Format("Successfully loaded achievement list. Count={0}.", _achievementCount));

                for (int _iter = 0; _iter < _achievementCount; _iter++)
                {
                    Debug.Log(string.Format("[Index {0}]: {1}", _iter, _achievements[_iter]));
                }
            });
Fetch Achievement Descriptions

These descriptions will be useful to display additional information to the player about achievements.

You can load all AchevementDescptions for achievements as below :

NPBinding.GameServices.LoadAchievementDescriptions((AchievementDescription[] _descriptions, string _error)=>{

                if (_descriptions == null)
                {
                    Debug.Log("Couldn't load achievement description list with error = " + _error);
                    return;
                }

                int        _descriptionCount    = _descriptions.Length;
                Debug.Log(string.Format("Successfully loaded achievement description list. Count={0}.", _descriptionCount));

                for (int _iter = 0; _iter < _descriptionCount; _iter++)
                {
                    Debug.Log(string.Format("[Index {0}]: {1}", _iter, _descriptions[_iter]));
                }
            });
Report Progress

Pass the progress percentage to report progress of an Achievement.

Make sure you set Number of Steps in the NPSettings while filling Achievement Meta Data.

Number of Steps for a one-shot or instant Achievement will be 1 and percentage you need to report to unlock is 100%.

For incremental achievements, number of steps will be steps required to unlock your achievement. You can access number of steps by below code :


int _noOfStepsRequiredToUnlock = NPBinding.GameServices.GetNoOfStepsForCompletingAchievement(_achievementGID);

Once you have number of steps to unlock, calculate the percentage to report.

double _progressPercentage = ((double)CURRENT_COMPLETE_STEPS/_noOfStepsRequiredToUnlock) * 100d;

In the above code, CURRENT_COMPLETE_STEPS is the number of steps player completed till now to unlock this achievement. For instant achievement, this will be 1.

Finally, we can report progress by below code :

// If its an incremental achievement, make sure you send a incremented cumulative value everytime you call this method
NPBinding.GameServices.ReportProgressWithGlobalID(GLOBAL_ACHIEVEMNT_ID, PROGRESS_PERCENTAGE, (bool _status, string _error)=>{

        if (_status)
        {
            AddNewResult(string.Format("Request to report progress of achievement with GID= {0} finished successfully.", _achievementGID));
            AppendResult(string.Format("Percentage completed= {0}.", _progress));
        }
        else
        {
            AddNewResult(string.Format("Request to report progress of achievement with GID= {0} failed.", _achievementGID));
            AppendResult(string.Format("Error= {0}.", _error.GetPrintableString()));
        }
    });

GLOBAL_ACHIEVEMNT_ID : The global ID of the achievement you want to report progress for.

PROGRESS_PERCENTAGE : Progress Percentage calculated for the achievement.

Show Achievements UI

You can display the default UI provided by native platform. If you are looking for displaying your own UI, you can make use of details form Achievements and Achievement Descriptions.

NPBinding.GameServices.ShowAchievementsUI((string _error)=>{
                Debug.Log("Achievements view dismissed.");
                if (!string.IsNullOrEmpty(_error))
                  Debug.Log(string.Format("Error= {0}.", _error.GetPrintableString()));
            });

Leaderboards

Leaderboards let your players to compete socially by sharing their scores to the world. Two actions can be done from Leaderboards API.

  1. Loading Scores (can give a User Scope and Time Scope).
  2. Reporting score to a particular leaderboard.
Load Scores of a Leaderboard

For Loading scores of a leaderboard with a global ID, you need to create Leaderboard Instance.

private Leaderboard CreateLeaderboardWithGlobalID (string _leaderboardGID)
        {
              m_curLeaderboard              = NPBinding.GameServices.CreateLeaderboardWithGlobalID(_leaderboardGID);
              m_curLeaderboard.MaxResults   = MAX_RESULTS_PER_PAGE;
            return m_curLeaderboard;
        }

Now you have an instance of Leaderboard.

Leaderboards data will be fetched in terms of pages. This is because there can be lot of results reported by many and pagination will help not to load complete data at once.

In the above code you can set MaxResults that needs to retrieve per page. There is a limitation on each platform about Page size.

On Android Max Results per page should be in between 1 and 25.

Now access the leaderboard scores by the below code :

// Create leaderboard instance
Leaderboard _curLeaderboard            = NPBinding.GameServices.CreateLeaderboardWithGlobalID(_leaderboardGID);

// Set max results to retrieve.
_curLeaderboard.MaxResults    = MAX_RESULTS_PER_PAGE;

_curLeaderboard.UserScope   = eLeaderboardUserScope.FRIENDS_ONLY;//Can set eLeaderboardUserScope.GLOBAL too.

// Load top scores
// OnLoadScoresFinished will receive a list of Scores once this finishes loading.
_curLeaderboard.LoadTopScores(OnLoadScoresFinished); 

// Load scores around player.
// OnLoadScoresFinished  will receive a list of Scores once this finishes loading.
_curLeaderboard.LoadPlayerCenteredScores(OnLoadScoresFinished);

// This fetches next pages of scores. This needs to be called only after any of above two calls.
_curLeaderboard.LoadMoreScores(eLeaderboardPageDirection.NEXT, OnLoadScoresFinished);

eLeaderboardPageDirection lets you to navigate among score result pages.

Report Score

You can report score either from Leaderboard instance or directly as below :

NPBinding.GameServices.ReportScoreWithGlobalID(GLOBAL_LEADERBOARD_ID, SCORE_TO_REPORT, (bool _success, string _error)=>{

  if (_success)
  {
      Debug.Log(string.Format("Request to report score to leaderboard with GID= {0} finished successfully.", _leaderboardGID));
      Debug.Log(string.Format("New score= {0}.", SCORE_TO_REPORT));
  }
  else
  {
      Debug.Log(string.Format("Request to report score to leaderboard with GID= {0} failed.", GLOBAL_LEADERBOARD_ID));
      Debug.Log(string.Format("Error= {0}.", _error.GetPrintableString()));
  }
});
Show Leaderboards UI

You can display the default UI provided by native platform. If you are looking for displaying your own UI, you can make use of details from Leaderboad Scores Method and method for getting user details by user identifier.

//Show Leaderboards UI
NPBinding.GameServices.ShowLeaderboardUIWithGlobalID(GLOBAL_LEADERBOARD_ID, TIME_SCOPE, (string _error)=>{
                Debug.Log("Leaderboard view dismissed.");
                Debug.Log(string.Format("Error= {0}.", _error.GetPrintableString()));
            });
Data Types

TIME_SCOPE : This can be

       eLeaderboardTimeScope.TODAY    // Fetch leaderboards existing TODAY
       eLeaderboardTimeScope.WEEK     // Fetch leaderboards existing Past WEEK
       eLeaderboardTimeScope.ALL_TIME // Fetch All Leaderboards

USER_SCOPE : This can be

  eLeaderboardUserScope.FRIENDS_ONLY   // Fetch Scores Among Friends Only
  eLeaderboardUserScope.GLOBAL         // Fetch Scores Globally

PAGE_DIRECTION : This can be

  eLeaderboardPageDirection.NEXT       // Fetch next page results
  eLeaderboardPageDirection.PREVIOUS   // Fetch previous page results

Advanced - Setting Leaderboards/Achievements Metadata Runtime

There can be cases where you need to set MetaData for Achievements and Leaderboards runtime instead of setting in NPSettings. This can be because you have a server which manages the data and you fetch it with an API.

In these cases Cross Platform Native Plugins provides few utility methods.

// Set leaderboards meta data
SetLeaderboardMetadataCollection(LEADERBOARDS_META_DATA_ARRAY);

// Set Achievements meta data
SetAchievementMetadataCollection(ACHIEVEMENTS_META_DATA_ARRAY);

Make sure you set these data after Awake() method

results matching ""

    No results matching ""