- Home /
C# OnPointerEnter and OnPointerExit (the latter not working!)
(Using Oculus and NewtonVR) I have a button which when you look at it it starts a timer (which displays as text UI objects) using OnPointerEnter. I want it to stop that timer when you look away, so I tried OnPointerExit but it's not working! Any idea why or any better/other ways of implementing this? The timer works and starts only when you look at it. Sorry about my disgusting variables!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class Timer : MonoBehaviour, IPointerEnterHandler
{
int minutes = 0;
int seconds = 0;
int minutes10 = 0;
int seconds10 = 0;
public Text minutesText;
public Text secondsText;
public Text minutes10Text;
public Text seconds10Text;
public GameObject minutesObject;
public GameObject secondsObject;
public GameObject minutes10Object;
public GameObject seconds10Object;
bool pointerEntered = false;
bool coroutineFinished = true;
private void Start()
{
minutesText = minutesObject.GetComponent<Text>();
secondsText = secondsObject.GetComponent<Text>();
minutes10Text = minutes10Object.GetComponent<Text>();
seconds10Text = seconds10Object.GetComponent<Text>();
}
public void OnPointerEnter(PointerEventData eventData)
{
pointerEntered = true;
}
public void OnPointerExit(PointerEventData eventData)
{
pointerEntered = false;
}
void Update()
{
if (pointerEntered && coroutineFinished)
{
coroutineFinished = false;
StartCoroutine(Pause());
}
}
IEnumerator Pause()
{
yield return new WaitForSeconds(1.0f);
if (seconds == 9)
{
seconds10++;
seconds = 0;
if (seconds10 == 6)
{
minutes++;
seconds10 = 0;
if (minutes == 10)
{
minutes10++;
minutes = 0;
}
}
}
else
{
seconds++;
}
minutesText.text = minutes.ToString();
secondsText.text = seconds.ToString();
minutes10Text.text = minutes10.ToString();
seconds10Text.text = seconds10.ToString();
coroutineFinished = true;
}
}
Answer by creganjordan292 · Jan 10, 2018 at 01:53 PM
You don't implement the IPointerExit interface.
Beat me to it. But yes, at the top of your class you need to add IPointerExitHandler after the IPointerEnterHandler.
Cheers,
~LegendBacon
What do you mean sorry? I added a boolean pointerEntered which should mean that the coroutine should only run if pointerEntered is true. How come it's not working?
In your class definition public class Timer : $$anonymous$$onoBehaviour, IPointerEnterHandler
you implement the IPointerEnterHandler. You need to change that line to this: public class Timer : $$anonymous$$onoBehaviour, IPointerEnterHandler, IPointerExitHandler
.
Your answer
![](https://koobas.hobune.stream/wayback/20220612150220im_/https://answers.unity.com/themes/thub/images/avi.jpg)