How to detect Google Cardboard Magnet Pull on Android

Google Cardboard and its knockoffs have a magnet slider that, when pulled, creates enough of a disturbance to be detected by the phone. In the Google Cardboard app, this is used as a way to click. How would I detect this in Unity? Google gives an example here, but it is for Java (native Android SDK development): https://developers.google.com/cardboard/get-started

This is to be used with the Durovis Dive plugin for the stereoscopic rendering.

I was able to figure out the answer on my own, with a bit more work. Hopefully this Question will help others who are also looking for this functionality.

There is a script on GitHub that works flawlessly, right here: https://github.com/CaseyB/UnityCardboardTrigger

This may be a little old but it took me awhile to figure out so here it is. The Cardboard SDK has built-in support to get trigger pulls, they are registered as events. You only need to add the event to your script. Add the event with OnEnable() and OnDisable() with the function you wish it to call.

Edit: Adding OnDisable() has odd effects on the sdk. I left it out and everything works well.

using UnityEngine;
using System.Collections;

public class Gun : MonoBehaviour {

	void OnEnable(){
		Cardboard.SDK.OnTrigger += TriggerPulled;
	}

	void OnDisable(){
		Cardboard.SDK.OnTrigger -= TriggerPulled;
	}

	void TriggerPulled() {
		Debug.Log("The trigger was pulled!");
	}
}

To use the scripts, simply apply a method to the delegate (MyEvent), in this method, you can see I call another script (Mover) method to react to the magnet event.

void myEvent() {
Debug.Log(“Got magnet event!”);
mover.setDoStart();
}

void Awake()
{
mover = GetComponent ();

	OnCardboardTrigger = myEvent;
	_sensorData = new List<Vector3>(WINDOW_SIZE);
	_offsets = new float[SEGMENT_SIZE];

}