How To Make A VR Button In Unity

One of my most popular articles is the one where I teach how to make a button in Aframe, so I thought I would make one for unity.

Finished Result

The first thing you want to do is make two cubes and position and scale them in such a way that they look like this:

We also want to create an empty game object somewhere underneath the button. Next, add a Rigidbody component to the empty game object and the pressable part of the button. Now add a spring component to the button and attach it to the empty game object. The default settings work just fine. Next, we want to constrain the button so it only moves up and down.


Next, add a collider to your hands and change the tag to a custom one, like Hand. This is so our button knows if it is intersecting our hands or the object it’s inside. Now all that’s left is to program our button. The script below handles everything button, it makes sure that the player doesn’t push the button too far or put their hand below the button and push it up. It also has a public variable that other scripts can check to see if its pressed.

 public class Button : MonoBehaviour
 {
     
     public float endstop;//how far down you want the button to be pressed before it triggers
     public bool Pressed;

     private Transform Location;
     private Vector3 StartPos;
     // Start is called before the first frame update
     void Start()
     {
         Location = GetComponent ();
         StartPos = Location.position;
     }
     void Update()
     {
         
        if (Location.position.y - StartPos.y< endstop && ReverseDirection == false) {//check to see if the button has been pressed all the way down

              Location.position= new Vector3(Location.position.x,endstop+StartPos.y,Location.position.z);
              GetComponent<Rigidbody>().constraints=RigidbodyConstraints.FreezeAll;
              Pressed = true;//update pressed
             }

             if (Location.position.y> StartPos.y && ReverseDirection == false) {
              Location.position= new Vector3(Location.position.x,StartPos.y,Location.position.z);
              GetComponent<Rigidbody>().constraints=RigidbodyConstraints.FreezeAll;
     }
     void OnCollisionExit(Collision collision)//check for when to unlock the button
     {
         Debug.Log("unlock");
         if (collision.gameObject.tag == "Hand") {
             GetComponent ().constraints &= ~RigidbodyConstraints.FreezePositionY; //Remove Y movement constraint.
             Pressed = false;//update pressed
         }
     }
 }

Now let’s make it do something. In my demo it destroys the world. Just kidding, it only changes some text:

public class TextYell : MonoBehaviour
{
public Button button;//refrence to button
void Update()
{
if(button.Pressed == true){
GetComponent().text = "WHAT HAVE YOU DONE!\nYOU'VE KILLED US ALL!!";
}
}
}

There you go, hope you liked it!

Liked it? Take a second to support WireWhiz on Patreon!
Become a patron at Patreon!