Archive for April 2015

More GameSparks and Unity Goodness

So if you’ve read the previous post and have a GameSparks project set up with leaderboards and achievements and a Unity project that handles adding achievements and scores you’re all set to complete the basics by adding functionality to display the high scores and the achievements a player has earned.

Add a new scene and set it up like the following:

leaderboards

All that’s needed is a few lines of code to display the scores in the leaderboard. Open the Leaderboards class and add the following:

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 Leaderboards : MonoBehaviour {

	// Use this for initialization
	void Start () {

        LeaderboardDataResponse response = new LeaderboardDataRequest().SetLeaderboardShortCode("HighScoreLeaderboard").SetEntryCount(10).Send();

        if(!response.HasErrors)
        {
            foreach (var entry in response.Data)
            {
                Text player = GameObject.Find("Player" + entry.Rank.ToString()).GetComponent<Text>();
                player.text = entry.UserName;
                Text score = GameObject.Find("Score" + entry.Rank.ToString()).GetComponent<Text>();
                score.text = entry.GetNumberValue("Score").ToString();
            }
        }
        else
        {
            Text player = GameObject.Find("Player1").GetComponent<Text>();
            player.text = "No Scores";
        }
	}

    public void OKButtonClick()
    {
        Application.LoadLevel("MainMenuScene");
    }
}

If you don’t have any scores other than the one from the previous post you should add some players through the GameSparks Test Harness and log some scores. To do so use the RegistrationRequest and AuthenticationRequest calls:

new player2

 

authentication

then add scores using the PostHighScoreEarned call under LogEvent:

posthighscore

Make sure you make all three calls in this order or your scores won’t be posted correctly.

On to achievements. I created a couple of additional achievements from the one created in the previous post:

achievements

Of course, we’ll need a scene to display them in:

achievementsscene

The graphic for each achievement is a UI Image object. We set the tag for the graphic to the achievement’s shortcode so we can find it when the scene loads.

Create a script and attach it to the scene’s Canvas as usual. 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 Achievements : MonoBehaviour {

	// Use this for initialization
	void Start ()
    {
        new ListAchievementsRequest().Send((response) =>
        {
            if (!response.HasErrors)
            {
                foreach (ListAchievementsResponse._Achievement achievement in response.Achievements)
                {
                    //if achievement hasn't been earned grey out icon
                    if (achievement.Earned.HasValue && !achievement.Earned.Value)
                    {
                        Image graphic = GameObject.FindGameObjectWithTag(achievement.ShortCode).GetComponent<Image>();
                        graphic.color = new Color(1f, 1f, 1f, .1f);
                    }
                }
            }
        });
	}

    public void OKButtonClick()
    {
        Application.LoadLevel("MainMenuScene");
    }

}

The ListAchievementsRequest call gets all the achievements set up in the system with a member for each achievement that tells if the player has earned it. If he hasn’t we change the alpha component of the color for the achievement’s graphic to indicate that the player hasn’t earned it.

That’s all it takes to get basic achievements and leaderboards working in your game. The project for this post is located here.

There is a lot more functionality in GameSparks that I’d like to cover. I’m thinking I might dig into some of the social functionality like friends and messages next. If you’ve looked into GameSparks and there’s something that you’d like to see covered let me know.

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.