Thursday, October 03, 2013

Unity Plugin (Android)

I've been working on creating a plugin for unity(Android). The latest versions of unity (4.x) provide clean way of accessing the java side of things on android.

If you want access to the android activity from android,  all you have to do is call the following..

AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject activity = unityPlayer.GetStatic("currentActivity");

This doesn't give us much of a head way... i.e, if you want to add any functionality you will have to extend the UnityPlayerActivity and add the functions you want and call them. But there is a more elegant way of doing it. You can just create a jar file from your android library and access its' functionality like so..

AndroidJavaClass _pluginClass = new AndroidJavaClass("com.vkgamedev.MyTestLib.MyTestLib");
_pluginClass.CallStatic("setGoogleProjectId", googleProjectId);

If your  library needs access to the android activity that's running, you can just send it in as a parameter to the java side as a AndroidJavaObject. You will need to create a static function that takes in a generic Object and sets the activity reference.

_pluginClass.CallStatic("initGamesSDK", activity,"yes");

The java side of things is pretty straight forward, just a singleton class with static functions to initialize and expose the functionality that your library provides, access them from unity using the JNI calls. 
If you want to send info back to unity from Android/java, just use the following function:

//this requires that you add unity-class.jar to your library project.
UnityPlayer.UnitySendMessage("GamesSDK", "onLogin", "Fail"); 

Java File for the Library

C# side of things for accessing the library (MyTest.cs)
If we want to be able to call unity functions from java side, we need to send the message to a particular object. So we have to create  a prefab that listens to these events and handles these messages.
Here is the code for plugin handler that has to be attached to an empty object that needs to be dragged into a scene to enable the plugin.

Be sure to name the Empty object as "GamesSDK" since that is the object we are sending the message to from the Java library code.
As you can see we have been able to create a basic flow for an android plugin without over riding the default activity provided by unity.