Search code examples
c#unity-game-enginevirtual-reality

gaze trigger event after n seconds - Unity


I have a 'pointer enter' event, but i only want the event to trigger if the gaze have been active on the object for n seconds.

public void PointerEnter() {
   // change scene if the gaze point have been active for n seconds.
}

Anyway to achive this ?

Just having a timeout wont do as it will still execute rather the pointer stay locked on the object or not.


Solution

  • You can use a boolean variable to keep state of when pointer has entered and exits by setting it to true and false. This boolean variable can then be checked in the Update function. When it is true, start a timer and if it becomes false during the timer, reset the timer to 0. Check when timer is more than the x second then load new scene.

    The example below assumes that PointerEnter is called when pointer is pointing and PointerExit when it's no longer pointing. The functions might be different depending on the VR plugin you're using but the rest of the code is the-same.

    const float nSecond = 2f;
    
    float timer = 0;
    bool entered = false;
    
    public void PointerEnter()
    {
        entered = true;
    }
    
    public void PointerExit()
    {
        entered = false;
    }
    
    void Update()
    {
        //If pointer is pointing on the object, start the timer
        if (entered)
        {
            //Increment timer
            timer += Time.deltaTime;
    
            //Load scene if counter has reached the nSecond
            if (timer > nSecond)
            {
                SceneManager.LoadScene("SceneName");
            }
        }
        else
        {
            //Reset timer when it's no longer pointing
            timer = 0;
        }
    }