I just started using Unity and I’m trying to trigger an action when the user makes the “tap” action on a Hololens. I tried using the following code but it doesn’t seem to work. I’m probably doing it completely wrong.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.WSA.Input;
public class FindDirection : MonoBehaviour
{
public Vector3 direction;
GestureRecognizer gesture;
void Start()
{
direction = transform.position;
}
void Update()
{
var headPosition = Camera.main.transform.position;
var gazeDirection = Camera.main.transform.forward;
RaycastHit hitInfo; //Information about the first object touched by the ray
bool directionChange = false;
gesture = new GestureRecognizer();
gesture.StartCapturingGestures();
gesture.Tapped += (s) =>
{
directionChange=true;
};
if (directionChange==true)
{
//the action I want it to do must be inserted here
}
}
}
You probably only want lines 23 through 28 to be done once. Right now you are doing them every frame, 60 frames per second adding a fresh copy of the anonymous directionChange = true delegate.
If I were to remove these lines from the update, would the program still read the tap input every time it happens? I believe it would only readyl it once.
I don’t know the API but it appears you are adding an anonymous delegate to the .Tapped event.
Generally this would be done once in either .Awake(), .Start() or .OnEnable().
If you want the scene to go away, you would want to undo it with a -= call in .OnDisable().
That entire process is a very common mechanism of subscribing to events. As long as you’re subscribed, the delegate will be called. I know nothing else about the API you’re using or your intended use case. It just seems very suspicious to be adding the same delegate callback 60 times per second.