So you want to integrate custom Android plugins written in Java, into a Vuforia-based Unity project…
In this post, we’ll show you how, and how to invoke methods defined in the Java plugin from a Unity C# script. The Image Targets sample is a starting point for a Unity project example.
Steps to follow
- Create a Unity project; for ease of reference we refer to it as “QcarWithPlugin.”
- Import the Image Targets sample package for Unity (Menu->Assets->Import custom package…)
- Double-click the Image-Targets scene in the project view, so that the three Image Targets and their associated teapot models appear in the scene view.
- Create a new Android project in Eclipse; for ease of reference we call it MyPlugin; we assume the main activity will then be called MyPluginActivity.
- Right-click on the project in Eclipse, go to Properties > Java Build Path > Libraries, and add the following two libraries as “external jars” (both located under the Assets/Plugins/Android/ folder of your Unity project):
- Open the MyPluginActivity.java file in Eclipse, and make the following code changes:
- Make MyPluginActivity extend QCARPlayerActivity instead of Activity (press Ctrl-Shift-O to automatically adjust the imports).
- Remove the line “setContentView(…)” from the onCreate() method.
- Add a custom public method called showMessage() to the MyPluginActivity class, and fill it with some code to show a Toast message with text.
The code of your MyPluginActivity should look like the following:
- Right-click on the project, go to Properties -> Android, tick the “IsLibrary” checkbox to turn your Android project into a library; this should make Eclipse generate a .JAR file (e.g., called “myplugin.jar”) and store it in the “/bin” folder of your Eclipse project.
- Open the “/bin” folder and copy the JAR library from that folder to the “Assets/Plugins/Android/” folder of your Unity project.
- Open and edit the AndroidManifest.xml file located in the same “Assets/Plugins/Android/” directory.
- Replace the name of the main activity with your fully qualified Activity name, e.g., “com.my.org.MyPluginActivity.”
- Create a C# script, call it MyPluginCaller for example, and attach it to each of your Image Targets in the scene (e.g., Chips, Stones, Tarmac).
- Copy the following code in your script, which will make your script invoke the showMessage() method of your MyPluginActivity class whenever a target is detected:
Now your project should be ready to build and run on your Android device!