Integrating GameSparks into a Unity game

A big selling point of video games is having things like leaderboards and awards/achievements. Unfortunately, implementing these things is a lot of work. Tools like Azure Mobile Services and 3rd party offerings make this a little easier, but it’s still a lot of work. I originally started looking at Azure Mobile Services, via bitrave, but recently stumbled across something that looked like it might be a bit easier, being built specifically for what I was looking to implement – GameSparks. I’m going to go over using the SDK in a couple of posts, each one being relatively short and sweet.

Obviously, the first thing that needs to be done is to download and install the SDK. Rather than rewrite something, just follow the instructions here and come back when you’re done. Go ahead, I’ll wait. 🙂

OK, so you should be all set up and able to authenticate against the service. The first thing we’ll need is some way to log in to the game. We have to have an ID for the player in order to track things like leaderboards and achievements. We’ll need a scene to allow the user to enter the data for a user ID and password:

login screen

Create a new scene and place some UI controls similarly to the layout in the picture. Notice that I’ve put a GameObject in the scene for the GameSparks functionality as the instructions above stated. Once you have the scene create a Login class and add the following to it:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using GameSparks.Api;
using GameSparks.Api.Messages;
using GameSparks.Api.Requests;
using GameSparks.Api.Responses;
using GameSparks.Core;

public class Login : MonoBehaviour {

    public InputField LoginIDText;
    public InputField EmailText;
    public InputField PasswordText;
    public Text LoginErrorText;

    public void CreateAccountButtonClick()
    {
        //ensure all items were entered
        if (LoginIDText.text.Length > 0 && EmailText.text.Length > 0 && PasswordText.text.Length > 0)
        {
            RegistrationResponse response = new RegistrationRequest().SetUserName(LoginIDText.text).SetDisplayName(LoginIDText.text).SetPassword(PasswordText.text).Send();

            if (!response.HasErrors)
            {
                Global.UserID = response.UserId;
                Application.LoadLevel("MainMenuScene");
            }
            else
                LoginErrorText.text = "All information must be entered";
        }
    }

    public void OKButtonClick()
    {
        //verify credentials
        if (LoginIDText.text.Length > 0 && PasswordText.text.Length > 0)
        {
            AuthenticationResponse response = new AuthenticationRequest().SetUserName(LoginIDText.text).SetPassword(PasswordText.text).Send();
            if (!response.HasErrors)
            {
                Global.UserID = response.UserId;
                Application.LoadLevel("MainMenuScene");
            }
            else
                LoginErrorText.text = "Incorrect credentials";
        }
    }

    public void ExitButtonClick()
    {
        Application.Quit();
    }
}

Note the references to the GameSparks namespaces added at the top. We’ll need these to send requests to the service. We have the members that we’ll link to our controls so we can retrieve the text in them and 3 methods for handling clicking on each button.

If the player is creating an account, we send the info to the GameSparks service using the RegistrationRequest object and assuming we get a valid response set a global (yes, I use globals. Don’t hate! :D) with the ID so we can use it later, then load the menu scene. If the player already has an account we use the AuthenticationRequest object and, if the credentials are correct, load the menu scene. Fairly straightforward stuff. Once you have the code entered, save and go back to Unity. Drag the class from the Project tab onto the Canvas in the Hierarchy and hook up all the events and drag the input fields onto the Login class members in the Inspector. If you’re not sure how to do this, head over to the Unity Tutorials site and learn the basics of working in the Unity IDE. If you’re really stuck let me know and I’ll try to walk you through the process. 🙂 The interesting stuff happens next.

Before we can use the Achievements and Leaderboards scenes we need to set up some achievements and leaderboards in GameSpark. In the GameSparks Configurator, click on Achievements, then the Add New “+” graphic:

gamesparksachievements

Add some info for the achievement:

achievementinfo

Click the Save button and you’re done with that part. You can add as many other achievements as you’d like of course.

Next we’ll need an event that’ll be called when an achievement is earned. Click on the Events item in the Configurator and create a new Event:

achievementevent

The ShortCode is the same as the Name here since the text area isn’t wide enough to show it. 🙁 We’ll send the Player’s ID and the shortcode for the achievement to a chunk of Cloud Code that’ll save the achievement. After you save the event, go ahead and click on the Cloud Code item. Under the Bindings | Events item, click on the PostPlayerAchievementEarned item and add the following code:

achievmentcloudcode

Save that and that’s it for the GameSparks side of things.

How do we tell GameSparks the player has earned an achievement? Good question, let’s implement that now. Create a new scene that we’ll use to fake earning an achievement (and adding to a leaderboard soon):

testscene

Add a script file call GameSparksTest and add the following to it:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using GameSparks.Api;
using GameSparks.Api.Messages;
using GameSparks.Api.Requests;
using GameSparks.Api.Responses;
using GameSparks.Core;



public class GameSparksTest : MonoBehaviour {
    public Text ResponseText;
    public void TestAchievementButtonClick()
    {
        LogEventRequest request = new LogEventRequest(); ;
        request.SetEventKey("PostPlayerAchievementEarned");
        request.SetEventAttribute("PlayerID", Global.UserID);
        request.SetEventAttribute("AchievementID", "PlayedGame");

        ResponseText.text = "";

        request.Send((response) =>
        {
            if (!response.HasErrors)
                ResponseText.text = "Achievement Added";
            else
                ResponseText.text = response.Errors.JSON;
        });

        if (ResponseText.text == "")
            ResponseText.text = "Response not received";

    }

}

Fairly straightforward. Create the LogRequest object, set the name of the event to be called, set the parameters, and send it off.

Leaderboards work in a similar fashion. Head back to the GameSparks Configurator and set up an event:

leaderboardevent

Then set up a leaderboard:

leaderboard

That’s it for the GameSparks side of things. Go back to the GameSparksTest class in your Unity project and add a handler for the TestLeaderboardButton (making sure to hook it up to the button):

public void TestLeaderboardsButtonClick()
{
    LogEventRequest request = new LogEventRequest();
    request.SetEventKey("PostHighScoreEarned");
    request.SetEventAttribute("Score", 10);

    request.Send((response) =>
    {
        if (!response.HasErrors)
            ResponseText.text = "High Score Posted";
        else
            ResponseText.text = response.Errors.JSON;
    });

    if (ResponseText.text == "")
        ResponseText.text = "Response not received";
}

It doesn’t get much simpler than that I think. You can use the Test Harness section of the GameSparks site to pull the data for the achievements and leaderboards for the player to verify that the data was saved. Using the Test Harness is pretty straightforward. You’ll have to make an authentication call, then use the List AchievementRequest under the Player section and the ListLeaderboardsRequest under the Leaderboards section, filling in the necessary information in the JSON.

I’ve put the Unity project for this post here. You’ll have to fill in your own GameSparks credentials of course. Feel free to ask any questions about what we’ve gone over.

Next post I’ll add functionality to pull and display the achievements for a player and display the leaderboard information. Take a stab at figuring it out beforehand if you’d like.

9 Comments

  1. Tiago Costa says:

    Hi,
    somehow the login system doesn’t work anymore, when I click on create account, or on Ok button, I get the error “Object reference not set to an instance of the object”, and I’m using your project.

    Is there any way to fix this?

  2. Mach X Games says:

    Did you set up a GameSparks game using the portal Configurator as the instructions I linked to in the 2nd paragraph stated? Nothing will work until you configure your game using the keys from your GameSparks project.

    • Tiago Costa says:

      Yes, I did that and still doens’t work, I’ll try something else and if I can fix it I’ll tell you.
      Ty for your quick response 🙂

  3. angelsm says:

    Great tutorial !! But I get this error: Assets/scripts/Login.cs(39,136): error CS1501: No overload for method `Send’ takes `0′ arguments

    Can you help me?

    • Mach X Games says:

      I just downloaded the project and it built fine. Is your code exactly like what is in the project? It could be a version difference in the GameSparks library.

      • angelsm says:

        You’re right! The GameSparks library was a different version. I’ve change it and it works.
        Now, I’m trying the second tutorial but I don’t get leaderboard works. I’ve follow it step by step and it doesn’t appear any score value in the list using GameSparks Test Harness. I don’t know how to do it and how to implement the score of my game. Can you help me again?

      • angelsm says:

        Sorry, but I’ve got the score values and the players I ‘ve made in the GameSparks Test Harness appear in the leardboard. I had made a mistake. Now, I need to know how I can implement the scores of my game. Thank you so much !!

  4. LukasSt says:

    Hey man, real nice tutorial! We are using GameSparks now for our game too, and it lacks examples about how to create more complex achievements likes achievements with progress (like buy 5 items). How could i have progress tracked for current user of some action made (item bought, enemies killed etc.) with GS? And even more so, how would it be possible to have a list of achievements displayed to show the progress (example: 4/5 items bought), and after the player bought 5th item, automatically the achievement would be earned and displayed (using their AchievementListener). Can’t find much info how to integrate all this, maybe you have any knowledge?

  5. robin says:

    Hey, I am following step by step the second post, its great but I got an run time error here it is

    “NullReferenceException: Object reference not set to an instance of an object
    GameSparks.Core.GSTypedResponse.get_HasErrors ()
    Leaderboards.Start () (at Assets/Scripts/Leaderboards.cs:18)”

    how to solve this?

Leave a Reply

You must be logged in to post a comment.