Sep 09

Android Java Plugin for Unity Tutorial

This tutorial will guide you through the process of creating a Java plugin for Unity when building an application or game for Android. Before writing this tutorial I used the following guide to make a working project of my own. Much credit goes to MatD for writing his guide, if anything isn’t clear in this tutorial please check his one, it might have some additional information I left out to simplify the process.

What I’ll be using in this tutorial and what you might need to complete it is the following:

  • Unity 4.x
  • Android SDK (API 10 or higher installed)
  • Eclipse 4.2.2

Step 1: The Java code

First of all, open up Unity and create a new project called PluginTutorial. You do not need to import any packages. Unity will create a folder structure for you. I put the project in the following directory:

  • C:\Users\Devon\Documents\PluginTutorial

Next up, in the \PluginTutorial\Assets\ folder create a folder called Plugins, and in that folder create another one called Android. Now open up your favorite text editor and create a file called PluginTest.java which you need to save in the \PluginTutorial\Assets\Plugins\Android\ folder.

The contents of this file are the following:

package com.test.app;
 
import com.unity3d.player.UnityPlayerActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.Config;
import android.util.Log;
public class PluginTest extends UnityPlayerActivity
{
    private static final String TAG = "PluginTest_Unity";
    private static int number = 0;
 
    @Override
    protected void onCreate(Bundle myBundle) {
        super.onCreate(myBundle);
 
    }
    @Override
    protected void onResume() {
        if (Config.DEBUG)
            Log.d(TAG, "onResume");
        super.onResume();
    }
    @Override
    protected void onPause()
    {
        super.onPause();
    }
    @Override
    protected void onStop() {
        if (Config.DEBUG)
            Log.d(TAG, "onStop");
        super.onStop();
    }
    public static int getNumber()
    {
        number++;
        return number;
    }
}

As you can see we don’t really do a lot here, this is a tutorial to get you started so we simply increment a number and return it (so our Unity app can call this function and receive the number).

Please note package com.test.app, this package name NEEDS to be the same in Unity! To change this, switch over to Unity and go to File > Build Settings

Start by selecting Android as the platform and click on Switch Platform. Then hit Add Current so we have an active scene for the app. When prompted to save call the file PluginTutorial.unity. Now select Player Settings… 

If you’re building something for a tablet it might be a good idea to change the Default Orientation to landscape mode, or you could select Auto Rotation. I’ve noticed that the unity app tends to go back to the homescreen when the current orientation is not the same as the one you’ve selected here.

Next up, click Other Settings and change the Bundle Identifier to match your package name, in our case edit com.Company.ProductName to com.test.app

Now switch back to your text editor and create a new file called AndroidManifest.xml which also goes into the \Android\ folder. The content of the file should be the following:

<?xml version="1.0" encoding="utf-8"?>
 
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.test.app"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />
    <application android:label="@string/app_name">
        <activity android:name=".PluginTest"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
Again, take note of the package and android:name properties.
Continuing on, we’re now ready to build and compile our Java program. Create a new file called build.xml and place it in the \Android\ folder. The contents are:
<?xml version="1.0" encoding="UTF-8"?>
 
<project name="CompilePluginTutorialAndroidJava">
    <!-- Change this in order to match your configuration -->
    <property name="sdk.dir" value="C:\android-sdk-windows"/>
    <property name="target" value="android-10"/>
    <property name="unity.androidplayer.jarfile" value="C:\Program Files (x86)\Unity\Editor\Data\PlaybackEngines\androiddevelopmentplayer\bin\classes.jar"/>
    <!-- Source directory -->
    <property name="source.dir" value="." />
    <!-- Output directory for .class files-->
    <property name="output.dir" value="./classes"/>
    <!-- Name of the jar to be created. Please note that the name should match the name of the class and the name
    placed in the AndroidManifest.xml-->
    <property name="output.jarfile" value="PluginTutorial.jar"/>
      <!-- Creates the output directories if they don't exist yet. -->
    <target name="-dirs"  depends="message">
        <echo>Creating output directory: ${output.dir} </echo>
        <mkdir dir="${output.dir}" />
    </target>
   <!-- Compiles this project's .java files into .class files. -->
    <target name="compile" depends="-dirs"
                description="Compiles project's .java files into .class files">
        <javac encoding="ascii" target="1.6" debug="true" destdir="${output.dir}" verbose="${verbose}" includeantruntime="false">
            <src path="${source.dir}" />
            <classpath>
                <pathelement location="${sdk.dir}\platforms\${target}\android.jar"/>
                <pathelement location="${unity.androidplayer.jarfile}"/>
            </classpath>
        </javac>
    </target>
    <target name="build-jar" depends="compile">
        <zip zipfile="${output.jarfile}"
            basedir="${output.dir}" />
    </target>
    <target name="clean-post-jar">
         <echo>Removing post-build-jar-clean</echo>
         <delete dir="${output.dir}"/>
    </target>
    <target name="clean" description="Removes output files created by other targets.">
        <delete dir="${output.dir}" verbose="${verbose}" />
    </target>
    <target name="message">
     <echo>Android Ant Build for Unity Android Plugin</echo>
        <echo>   message:      Displays this message.</echo>
        <echo>   clean:     Removes output files created by other targets.</echo>
        <echo>   compile:   Compiles project's .java files into .class files.</echo>
        <echo>   build-jar: Compiles project's .class files into .jar file.</echo>
    </target>
</project>
There are three things you need to edit here:
  • <property name=”sdk.dir” value=”C:\android-sdk-windows”/> this is the SDK directory for Android, sometimes it might also be <property name=”sdk.dir” value=”C:\android\sdk”/>
  • <property name=”source.dir” value=”.” /> needs to be your folder directory, e.g. mine is <property name=”source.dir” value=”C:\Users\Devon\Documents\PluginTutorial\Assets\Plugins\Android” />
  • The output dir: <property name=”output.dir” value=”C:\Users\Devon\Documents\PluginTutoroal\Assets\Plugins\Android\classes”/>
  • The JAR filename: <property name=”output.jarfile” value=”PluginTutorial.jar”/>

Now open up Eclipse and go to File > New > Other, in the wizard select Java Project from Existing Ant Buildfile (this might be nested in the Java directory). Select Browse and open up your build.xml file. This will create a new Eclipse project for you.

Open up the PluginTest.java file found in Android > (default package). Hover over the package com.test.app; line and select move to the appropriate package.

Now select the play button with a briefcase and select External Tools Configuration.

In the main tab, select Browse File System… and navigate to the build.xml file. Next up in the Targets tab check build-jar and clean-post jar. Now hit Apply and then hit Run.

Note that if you get an error about JAVA_HOME, go to the JRE tab and select Installed JREs… Then click add, select Standard VM and then Directory… Navigate to the Java directory (usually something like C:\Program Files\Java\ and select your jdk folder (in my case jdk1.7.0_17). Click OK and back in the JRE tab select your jdk in the Separate JRE dropdown box.

You will now have everything Unity needs to be able to communicate with your Java program. Notice the PluginTutorial.jar file in your \Plugins\Android\ folder.

Step 2: The Unity Code

Next up we will create a C# script in Unity to actually grab the number from the java code. Switch over to Unity and create a new C# script in the assets folder called NumberExample. The contents of this file:

using UnityEngine;
using System.Collections;
 
public class NumberExample : MonoBehaviour {
	public GUIText number_output_text;
    AndroidJavaClass pluginTutorialActivityJavaClass;
 
    void Start () 
	{
        AndroidJNI.AttachCurrentThread();
        pluginTutorialActivityJavaClass = new AndroidJavaClass("com.test.app.PluginTest");
    }
 
    void Update()
	{
		int number = pluginTutorialActivityJavaClass.CallStatic("getNumber");
		number_output_text.text = "nr: " + number;
    }
}

Now drag this script onto the Main Camera and create a new GUI text GameObject. Drag it onto the Number_output_text field of the script attached to the Main Camera.

Step 3: Running the app

Now go to File > Build & Run and select Build and Run. Call the apk PluginTutorial if asked for a name. And that’s it! You’ll see the number increasing on your Android device.

If you run into any problems feel free to ask questions in the comments section and I’ll try to help out as much as I can. You can download my files for the project by clicking the following link: Plugin Tutorial Project.