About

Unity3D is a multi-platform 3D game engine. Google Cardboard is a cheap virtual reality solution which lets you turn any phone into the viewer, and on the side of the Google Cardboard version 1 device is a special magnetic button. The way it works: almost all smartphones have a compass, so when you put a magnet near the phone, the compass is affected. The code below is for Unity to detect when the button has been pushed.

Please note that Google Cardboard version 2 has a touch button instead of a magnet, because the magnet didn't seem to work on all phones and was prone to calibration issues.

Acknowledgements: This code was modified from some amazing source code by Casey Borders which you can download from github. Casey's C# "MagnetSensor" class inherits MonoBehaviour and has it's own listener, meaning you must drag it onto a GameObject and add a listener class. This version I've added some comments, removed the listener and made it a standalone class with static function, meaning you don't need to drag it onto the scene - but you do have to call "EnableSensor(true)" once then "CheckIfPressed()" continually from elsewhere to detect when it is set off.

Detecting Google Cardboard Magnetic Button Click - Shorter Version

Acknowledgements: This code by Andrew Whyte from Secret Ingredient Games who found the code by Casey and I and made a great reimplementation. I have left the original, but this one might be better. Thans Andrew! Check out his amazing mobile game: tilt golf