Learn to Build
Unity Games and Kii and Win $10K & Global Distribution for Your New Game!
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.
The focus of this article is on the backend
components and contains information for developers to quickly build scalable
games on Kii Game Cloud.
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());
}
else
{
Debug.Log("Signup succeeded");
}
});
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());
}
else
{
Debug.Log("Login succeeded");
}
});
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);
}
user via Facebook ( -> KiiUser.CurrentUser)
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);
KiiQuery query = new KiiQuery(clause); string sortKey = "_calculated." + distanceField;
query.SortByAsc(sortKey);
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);
try
{
obj.Acl(ObjectAction.READ_EXISTING_OBJECT).Subject(
KiiAnonymousUser.Get()).Save(ACLOperation.GRANT);
}
catch (Exception e)
{
}
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:
public static void EndOfLevel(float gameTime, int level)
{
KiiEvent ev = KiiAnalytics.NewEvent("end_of_level");
ev ["user"] = user.Username;
ev ["time"] = gameTime;
ev ["level"] = level;
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!
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.