- Home /
Long press stationary
How would i do a long press?
My algorithm i am trying to do goes like this (but doesnt seem to work)
if(Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Began) {touch0BeginTime = Time.time;}
if(Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Stationary && (Time.time - touch0BeginTime)) {//long press code here}
Why doesn't this work?
I've ran into another odd problem, whenever i put guiText.text = "random text";, the entire iff block seems to be skipped over. Without that code, it works fine. Why is this? guiText is a guiText object that works fine for other methods.
What could make code be skipped over?
The code was skipped because of a null reference. It irrationally skips code due to null references similar to segmentation faults in c++
Answer by deepthinker · May 04, 2012 at 08:15 AM
Try this:
private var longPressDetected: boolean = false;
private var newTouch: boolean = false;
private var touchTime: float;
function Start () {
}
function Update () {
if (Input.touchCount == 1){
var touch: Touch = Input.GetTouch(0);
if(touch.phase==TouchPhase.Began){
newTouch = true;
touchTime = Time.time;
Debug.Log('touchTime='+touchTime);
}else if (touch.phase == TouchPhase.Stationary){
if(newTouch==true && Time.time-touchTime>1){
Debug.Log('longpress detected');
newTouch = false;
longPressDetected = true;
}else if (newTouch == false && longPressDetected==false){ // began not detected
newTouch = true;
touchTime = Time.time;
Debug.Log('touchTime='+touchTime);
}
}else{
newTouch = false;
longPressDetected = false;
Debug.Log('setting newTouch false');
}
}
}
Answer by DaveA · Mar 16, 2012 at 12:03 AM
(Time.time - touch0BeginTime) will be non-zero, hence 'true' in the next frame. You need to compare it to some real amount of time, like
var longPressTime = 2.0;
(Time.time - touch0BeginTime) > longPressTime
sorry i forgot to type that, i have it in my code. just thought too quickly. Why would it skip my code though? And is there an order to using touchphases and such? Like if i test if touchphase == end before touchphase.began?
Thanks for the answers but i found a way to do it. It's similar to "timidguy" but i did checks in one line and had code to check my touch phases in order (doing them out of order seems to make unity skip execution of code between the out of order checks. And example is checking if TouchPhase.Began after checking TouchPhase.$$anonymous$$oved. It's odd but unity hates it.
Your answer
![](https://koobas.hobune.stream/wayback/20220613065152im_/https://answers.unity.com/themes/thub/images/avi.jpg)