Kii Unity 3D (.NET) SDK now supports async calls!

Rejoice Unity 3D developers! Async calls are here :)

Kii Cloud integrates with Unity

Some time ago we released a Unity SDK for Kii Cloud to allow game developers to quickly support a full blown back-end in their games. The SDK is a C# based .NET assembly that can be included as a plugin in your Unity project. Even though most of our features were supported at the time of the release all method calls were blocking calls so your game could suffer for some hiccups while accessing the Kii Cloud API.

Some of us used a workaround to avoid these halts in the game by using c#’s Actions, delegates and StartCoroutine to execute the calls on a separate thread. This is how it works in case you have a blocking call that you want to “unblock”:


void OnGUI () {

    if (GUILayout.Button ("Login", GUILayout.MinHeight (50), GUILayout.MinWidth (100))) {
        login ();
    }

    private void login () {
        Action callback = delegate(string s) {
            loginCallback (s);};
        StartCoroutine (loginBlocking (callback));
    }

    private void loginCallback (string errorMessage) {
        if (errorMessage == null) {
            Debug.Log ("Login completed");
            Application.LoadLevel ("MainGameScene");
        } else {
            Debug.Log ("Login failed : " + errorMessage);
        }
    }

    IEnumerator loginBlocking (Action callback) {
        string errText = null;
        try {
            KiiUser.LogIn (username, password);
        } catch (CloudException e) {
            errText = e.Message;
        }
        yield return null;
        callback (errText);
        yield return null;
    }
}

However, this is past history now. With the release of Unity Storage SDK v1.3.0 you can now elegantly use lambda expressions to call our API using callbacks. Let’s take a look at how the code below changes and how much more concise and elegant it gets:


public void OnGUI () {
   bool loginClicked = GUI.Button(loginButtonRect, "Login");
   if (loginClicked) {
      performLogin(username, password);
      return;
   }
}

void performLogin (string username, string password) {
   message = "Login...";
   KiiUser.LogIn(username, password, (KiiUser user, Exception e) => {
      if (e != null) {
         message = "Login failed " + e.ToString();
         return;
      }
      message = "Login succeeded";
   });
}

Notice that the callback is passed as the lambda’s right side of the expression. And that the same kind of lambda based callbacks can be used across the API (eg. for data management API calls).

We trust that this addition will make you code more elegant not to mention that it will avoid blocking issues mentioned above.

Happy coding!