SteamVR: Handling Vive Controller Input in Unity

Rushil Reddy

Following from our previous tutorial on how to set up your Vive for Unity development we are now going to learn how to get input from the Vive Controllers.

First, create a new Unity C# script(Right click in project view and Create>New Script) and call it ControllerManager.

Double click to edit in your prefered editor and write in the following.

using UnityEngine;

using System.Collections;

public class ControllerManager : MonoBehaviour {

public bool triggerButtonDown = false;

private Valve.VR.EVRButtonId triggerButton = Valve.VR.EVRButtonId.k_EButton_SteamVR_Trigger;

private SteamVR_Controller.Device controller {

get { return SteamVR_Controller.Input((int)trackedObj.index);

}

}

private SteamVR_TrackedObject trackedObj;

void Start() {

trackedObj = GetComponent();

}

void Update() {

if (controller == null) {

Debug.Log("Controller not initialized");

return;

}

triggerButtonDown = controller.GetPressDown(triggerButton);

if (triggerButtonDown) {

Debug.Log("Fire");

}

}

}

Our first step in the script is to make sure we have a variable that we can access the controller with. Same with the trigger button. Next we use the built in SteamVR calls to know when trigger is pressed. The update function in Unity is called every frame so we use it to check if our trigger is pressed and finally we added a debug so that when you play you’ll see the results of the script.

Hit play and pull the trigger, you should see “Fire” appear in the console.