Archive for August, 2011

Accessing the Android Compass through Unity 3D.

OK, let’s go ahead and get this out of the way. This post is not for beginners or the faint of heart. There is no way to access Android’s Magnetic Field Sensor (aka the compass) directly from Unity, so in order to do that we’re going to have to write a custom plugin. This is not an easy task, and I honestly don’t know how well I can explain it – so… stick with me and hopefully we’ll get through this together. (Note: At the time of this writing I’m using Unity 3.4 so if you’re a traveler from the distant future, I don’t know how much of this will still be valid)

Quick Overview of custom plug-ins:

Writing a custom plugin is very poorly documented, and anyone who does it pretty much has to figure it all out by themselves. For Android, here’s the process:

1. Write a custom Java jar file.
2. Write a C(++) library using JNI to access the jar file and compile it into a .so file using Android NDK
3. Import the DLL (.so file) into C# script inside unity and access all the magic.

Now, I’m not that great of a C developer, so I opted to do the following instead:

1. Write a custom Java jar file.
2. Use the AndroidJNI helper function embedded in Unity to access the jar file.

The latter method is the one we’re going to use today. Continue reading ‘Accessing the Android Compass through Unity 3D.’

Advertisements