Game Cloud for Unity

Mobile gaming is one of the fast growing markets. According to industry analysts, mobile and online game sectors could grow at a compound annual growth rate of 23% to $60 billion by 2017.

This means that game developers have a huge opportunity. However, only a small percent of total games actually become successful. Based on our experience working with many game developers, we have found that practically all successful games have some common elements: they start with a great idea, have an awesome user experience, and, they have a scalable backend to support any spikes in growth and ongoing performance needs. They also create a strong user acquisition machine. Finally, the successful games gather information about player behaviors and usage, and monetize intelligently based off of those insights.

Kii provides a complete game cloud available out of the box — including backend tools, insights and a distribution package to help developers aggressively distribute their games.

Who is this document for?

This document is for developers interested in building mobile games. The document focuses on the backend components and contains information for developers to quickly build scalable games on Kii Game Cloud.

While the the front end/client part for building mobile games is not the focus of this document, Kii has partnered with Unity - a gaming engine - to provide more complete solution for game developers. So there will be references to the Unity SDK in this document

There are also few sample and demo games that you can re-use or play with to get familiar with our SDKs

Getting Started

Getting started is easy and sign-up is free at developer.kii.com. To create your first app and plug in the Kii SDK, follow the simple instructions here.

This page serves as a quick reference and many snippets are based on our full Unity + Kii open source tutorial UnityAngryBotsKii (based on the AngryBots demo), which can be found on our Github Project Page.

Note: If you would like to dive deeper, we have full guides and reference docs available at any time.

Player Management

Being able to manage users (i.e. allowing them to sign up and log in) is essential for keeping track of scores, level progress and accessing the user's information across devices or platforms. Fortunately, this process is very simple using Kii SDK and can be accomplished in just a few lines of code.

Sign up a user

In order to create a user, check out the following snippet:

KiiUser.Builder builder = KiiUser.BuilderWithName(username);
builder.WithEmail(email);
KiiUser usr = builder.Build();
usr.Register(password, (KiiUser user, Exception e) =>
{
    if (e != null)
    {
        Debug.LogError("Signup failed: " + e.ToString());
        // process error
    }
    else
    {
        Debug.Log("Signup succeeded");
        // do something with user, it's a valid user now
    }
});

Authenticate a user

Similarly, in order to log a user in:

KiiUser.LogIn(username,password, (KiiUser user, Exception e) =>
{
    if (e != null)
    {
        Debug.LogError("Login failed: " + e.ToString());
        // process error
    }
    else
    {
        Debug.Log("Login succeeded");
        // do something with user, it's a valid user now
    }
});

Social Login with Facebook

You use Facebook to on-board your users in your Kii based game. In order to do that you need to add the Facebook Unity SDK to your game and then retrieve a Facebook token after user authentication. With that token you can on-board a user to Kii Cloud and get a valid Kii user:

KiiUser user = null;
try
{
    user = KiiUser.LoginWithFacebookToken(facebookToken);
}
catch(Exception e)
{
    Debug.Log(e.StackTrace);
}
// Now you have a logged in Kii user via Facebook ( -> KiiUser.CurrentUser)
// And you can update the user attributes from Facebook data
KiiUser.ChangeEmail(facebookEmail);
KiiUser.ChangePhone(facebookPhone);
user.Displayname = facebookName;
user.Update();
Debug.Log("Current user email is: " + KiiUser.CurrentUser.Email);
Debug.Log("Current user name is: " + KiiUser.CurrentUser.Displayname);
Debug.Log("Current user phone is: " + KiiUser.CurrentUser.Phone);

It is required that you enter the Facebook app id in your app settings at the developer console as explained in steps 1, 2 and 3 here before using this method.

Store Game Data

Kii SDK provides you with a very flexible JSON-based data store that is totally schemaless. Any key/value pair can be stored, nested and attached to users or other objects, allowing you to store all the data created or used within your game.

This type of storage is great for tracking user progress, creating leaderboards or storing and modifying game configuration remotely.

In the following example, we're creating a score to be uploaded to the leaderboard:

public void sendScore(int score)
{
    KiiUser user = KiiUser.CurrentUser;
    KiiBucket bucket = Kii.Bucket("scores");
    KiiObject kiiObj = bucket.NewKiiObject();
    kiiObj["score"] = score;
    kiiObj["username"] =  user.Username;
    kiiObj.Save((KiiObject obj, Exception e) =>
    {
        if (e != null)
        {
            Debug.LogError("Failed to save score" + e.ToString());
        }
        else
        {
            Debug.Log("Score sent");
        }
    });
}

Retrieve Game Data

Of course, once your data is stored - you need a way to get it out and use it in a meaningful way! Querying for data is very simple, and you can even create parameters to build a SQL-like query for retrieving data.

Check out this example, where we query for the top 10 scores to display in our leaderboard:

KiiBucket bucket = Kii.Bucket("scores");
KiiQuery query = new KiiQuery();
query.SortByDesc("score");
query.Limit = 10;
bucket.Query(query, (KiiQueryResult<KiiObject> list, Exception e) =>
{
    if (e != null)
    {
        Debug.LogError("Failed to query " + e.ToString());
    }
    else
    {
        Debug.Log("Query succeeded");
        int i = 0;
        foreach (KiiObject obj in list)
        {
            int score = obj.GetInt("score");
            string username = obj.GetString("username");
            DisplayScoreLine(i++, username, score);
        }
    }
});

Geolocation

Adding new dimensions to your game can bring more customization and even a personalized feel to your game. Kii allows you to attach location coordinates to any object being stored in the cloud, giving you an opportunity to leverage location within your game.

In this case, we are attaching coordinates to the score objects. This will allow us to see the highest scoring competitors within the user's area (i.e. 100km).

Storing Geo Coordinates

Here is how you can attach a coordinate to a score object:

public void sendScore(int score)
{
    KiiGeoPoint userLocation = new KiiGeoPoint(GetLatitude(), GetLongitude());
    KiiUser user = KiiUser.CurrentUser;
    KiiBucket bucket = Kii.Bucket("scores");
    KiiObject kiiObj = bucket.NewKiiObject();
    kiiObj["score"] = score;
    kiiObj["username"] =  user.Username;
    kiiObj.SetGeoPoint("location", userLocation);
    kiiObj.Save((KiiObject obj, Exception e) =>
    {
        if (e != null)
        {
            Debug.LogError("Failed to save score" + e.ToString());
        }
        else
        {
            Debug.Log("Score sent");
        }
    });
}

Querying for nearby objects

To search for scores within 100km of a given location, you can perform a query that looks something like:

KiiBucket bucket = Kii.Bucket("scores");
string distanceField = "distance_from_center";
KiiGeoPoint center = new KiiGeoPoint(GetLatitude(), GetLongitude());
KiiClause clause = KiiClause.GeoDistance("location", center, 100000, distanceField);

// Create a query instance and set the sorting order (closer first)
KiiQuery query = new KiiQuery(clause);
string sortKey = "_calculated." + distanceField;
query.SortByAsc(sortKey);

// Execute GeoDistance query
bucket.Query(query, (KiiQueryResult<KiiObject> list, Exception e) =>
{
    if (e != null)
    {
        Debug.LogError("Failed to query " + e.ToString());
    }
    else
    {
        Debug.Log("Query succeeded");
        int i = 0;
        foreach (KiiObject obj in list)
        {
            int score = obj.GetInt("score");
            string username = obj.GetString("username");
            DisplayScoreLine(i++, username, score);
        }
    }
});

Access Control

Being able to control who can read/write certain data within your game is critical for every app. Kii provides tools to do this easily, from default scopes to granting permissions on buckets to full ACLs (Access Control Lists) for individual objects. You can always be sure that the data being created by your game is only being accessed by the proper users.

Although there are many default permissions set out of the box, here is a quick example for altering the ACL of a single object:

Uri objUri = new Uri("a_public_game_object");
KiiObject obj = KiiObject.CreateByUri(objUri);

// Allow anonymous users to read the object
try
{
  obj.Acl(ObjectAction.READ_EXISTING_OBJECT).Subject(KiiAnonymousUser.Get())
        .Save(ACLOperation.GRANT);
}
catch (Exception e)
{
  // handle error.
}

Custom Analytics

For game developers looking to compete in the app stores, it's critical to understand the ins and outs of your game. How much are users playing certain levels? Are some levels too hard? Which purchases are they making the most? Answering these questions will help you not only improve your game, but can give you insight into how to better monetize your game.

These types of questions will vary from game to game, so you need to be able to track these in your own terms. Kii provides two different types of analytics, both of which are completely customizable based on your game rather than being forced to use template analytics defined by the provider

Event Analytics

Event analytics are very much in line with the traditional concept of analytics. How many times has this level been played? How much has the user been in multiplayer mode? You can track single events across all your users to answer these types of questions.

In order to track these types of events, you can use a simple code snippet like:

// Send Analytics event for end of level time
public static void EndOfLevel(float gameTime, int level)
{
     KiiEvent ev = KiiAnalytics.NewEvent("end_of_level");

     // Set key-value pairs
     ev ["user"] = user.Username;
     ev ["time"] = gameTime;
     ev ["level"] = level;

     // Upload Event Data to Kii Cloud
     try
     {
        KiiAnalytics.Upload(ev);
     }
     catch (Exception e)
     {
        Debug.LogError("Unable to upload analytics event to Kii Cloud: " + e.ToString());
     }        
}

Note: this requires you to build and deploy your game with this event tracking in the code. What happens if you need to start tracking new metrics after you have launched? See Game Data Analytics below!

Game Data Analytics

Your game generates data every time your user finishes a level, posts a score, or completes a transaction. Imagine being able to run complex analytics on all this data that is generated on a daily basis at any point in your app's lifecycle? That's what Kii's Data Analytics provides.

Don't worry about changing code and redeploying your game with new event tracking every time you think of a new metric. Simply slice your data using a web-based configuration portal on the fly without having to redeploy. Whatever data is being stored in your app can be analyzed at any time!

Other Benefits

Team Collaboration

Kii Cloud provides an in-depth developer portal for managing your game, seeing statistics and analytics, browsing data and more. We know that games are often the product of more than just one person - so give your team access to all the tools and resources provided by Kii Cloud simply by adding them to your team in the Kii developer portal.

Reliability & Scalability

You never know how many users your game will have at launch, or attract over time. With Kii Cloud, you don’t need to worry about it. Our highly reliable, scalable mobile backend is designed specifically to meet the needs of mobile game developers. Pricing also scales as you grow, allowing you to build and test for free then only pay when your app starts to grow.

One of Kii's largest and longest customers is NTT docomo, Japan's largest telecommunications carrier. Known for their reliability, NTT docomo has trusted Kii to scale to millions of users with ease. As your users grow, you want to be sure that you will have high availability and fast performance. We'll take care of that while you focus on your game!

Kii to China

Once your app is built, it’s up to you to get it into users’ hands. Distributing your Android apps within China can be a particularly difficult challenge, where Google Play has little to no reach.

Using Kii to China, you can distribute your app across dozens of app stores within China. Kii can provide not only translation and distribution, but also help get your app connected to payment mechanisms throughout the stores. Learn more about Kii to China here.

Next Steps

If you have not already done so, head over to developer.kii.com to sign up for a free Kii game cloud account. Within minutes, you can have a cloud-connected game up and running!

To help get you started, we have a few Unity demos so you can get familiar with our Unity SDK:

  • KiiUnitySDKSamples - A generic Unity demo that systematically shows all Kii Cloud API calls via the Unity SDK. It’s not attached to a game, but it’s a Unity project that runs without modification, exposing a Unity-based GUI for interaction.

  • UnityAngryBotsKii - Based on the official Unity 3D 4.3 AngryBots demo game, this project makes use of Kii Cloud via the Unity SDK. The demo is under development but it already showcases several Kii features.

  • HelloKii-Unity - A project that shows basic user management and data management (including queries) in the context of a simple breakout game.

  • Product demo that goes over the functionality

Kii’s game cloud provides all the tools you need to add cloud connectivity to your mobile game. From Unity integration to player management, custom data and even analytics, you can add great new features to your game faster than ever.