Tag Archives: managed dll

Unity 3D: Using Java classes/code

With Unity 3D you can use Java code. Here is a simple example how to use Java classes/code with Unity. Note that this tutorial only works with managed DLL files! If you want to use unmanaged DLL files you best have a look at the tutorial on the Unity 3D page here.

Create the Java class

First we create a Java class for testing:

package android.unity.plugin;

public class MyJava {

public MyJava() {
}

public String sayTokyo() {
return "Tokyo";
}

}

Export it to JAR

Export this class to a JAR file. You can do this with Eclipse in the package explorer by clicking the right mouse button on the class and choose Export -> JAR File. You do notneed to set any special options. Just define your desired dll file name and click export.

Convert it to DLL

Next go to IKVM.NET. Download and install this software. With IKVM you can convert JAR files into DLL files. This is what we need to do in order to be able to use the Java code with Unity.

Make sure to add the /bin path of IKVM to your System Environment Variable. It will look something like this:
C:\Users\de\Development\ikvm-7.0.4335.0\bin

Open a command prompt (CMD) and go to the directory where the previously exported JAR file is located. Then enter following command to convert the JAR file to a DLL file:

C:\Users\de>cd Desktop
C:\Users\de\Desktop>ikvmc -out:MyJava.dll MyJava.jar
C:\Users\de\Desktop>

When this command has been executed you have the MyJava.dll file which now can be used in Unity (this DLL file is a so called „managed dll“ file).

The Unity 3D stuff

Open Unity and import the MyJava.dll to your Assets folder. I copied mine to the Plugins sub folder but as far as I know this is not necessary.

I am not sure if this step is necessary but I did it anyways: Copy all the .dll files from the IKVM folder to the Assets/Plugins folder in Unity.

Create a .cs script – MyManagedJavaPlugin.cs – with Unity with the following content:

using UnityEngine;
using android.unity.plugin;

public class MyManagedJavaPlugin : MonoBehaviour {

void Awake() {
MyJava obj = new MyJava();
print(obj.sayTokyo());
}

}

android.unity.plugin has to be the namespace you used when you created the Java project with Eclipse.

Next you can attach the MyManagedJavaPlugin.cs script to an object in your Unity scene. Hit the play button in Unity and you will see that when the „Awake“ action is happening in Unity the sayTokyo() method will be called. The string „Tokyo“ will then be output in your Unity console.

That’s it for this tutorial. From now on you can modify your script and classes to fit your needs.