VERY weird touch responses. BUG?

Have I found a bug in unity?
i wrote this script to detect swipes / tap to be calculated by the distance between the beginning of the touch and the end of the touch.If I move left or right more than 100 units, then it is a swipe, other wise its a tap.

The problem is that when I tap the screen, it understands that it is a tap, but it also think that it is a swipe.

So when I tap the screen, console:

Debug.Log message : tap

Debug.Log message : swipe

//////

Debug.Log message : tap

Debug.Log message : swipe

///////

But when I swipe, it is fine. console:

Debug.Log message : swipe

///////

Debug.Log message : swipe

///////

Here is the code:

// I put this code in a GUI function because I use some gui labels, and I don’t want to put it in update() because it might cause error if it updates while it is in the middle of the touch.

//float distance = 0

                            foreach (Touch t in Input.touches) {
								
										if (t.phase == TouchPhase.Began) {
												distance = t.position.x;
										} 
										if (t.phase == TouchPhase.Ended) {
												distance = distance - t.position.x;
												if (distance > 100 || distance < -100) {
												Debug.Log ("swipe");
												} else {
												Debug.Log ("tap");
												}
												distance = 0;
										}									
								}

any idea?

I suspect your problem comes because you’ve put it in OnGUI, which is called multiple times per frame - for each “tap” that ends you’re therefore subtracting the position several times and always recording a distance of < -100.

Don’t ever include code logic in OnGUI - only put in GUI code.