Displaying the Device Compass in Unity

In my last Unity post we looked at integrating the accelerometers in a Unity app. In this post we look at integrating the magnetometer. A couple of years ago I published a magnetometer application in the Windows Phone Store. That app shows the magnetometer readings in 3D in relation to the orientation of the phone. The magnetometer sensor is how your device senses true north for the compass. For some devices (like my Nokia 1520), the Unity magnetometer API hides the 3D vector and only gives you access to the 2D vector “compass” data. I’ll live with that for now.
In Unity, it’s easy to get access to the magnetometer data. I start with much of the same code from my accelerometer app to display the compass in relationship to the orientation of my device. The first update is to enable the compass hardware with the following line.

According to the documentation you also need to enable the location services

The only other update is to subtract the trueHeading value from the result of the accelerometer calculated zangle variable.

The complete magnetometer code asset is listed here.

Attach this asset to any Unity GameObject and it will follow true north. Here is an example of the results.

The following two tabs change content below.
  • Emilio Luiz

    Thx Bro,

    helped me a lot

  • Dávid Bocsa


    I got some problems with this script. I scaled a cube, looks like a needle. Attached this script to this object, but it works badly. Like pretty badly. Could you update your demo as a package? Would be a great help. Thanks! 🙂

    • Bary

      Hi David, I’ll see if I can do that. I highly suspect that your issue is tied to the hardware. I remember when playing around with different devices that not all compasses were the same.

      • Dávid Bocsa

        tried some free apps from the store, they worked pretty well.

      • Dávid Bocsa

        Hi Bary, have you found out anything? 🙂