How to avoid delay after TouchPhase.Ended?

I’m trying to create a brake pedal on mobile and I have run into a problem. There is a big delay ( 2-3 seconds) between the moment I release the button and the moment when the end of the touch is detected. How can I improve this? Should I use something else instead of raycasting?

Here is the code I’m using:

using UnityEngine;
using System.Collections;

public class CarBrakes : MonoBehaviour {

	public CarController carController;

	private bool brakesArePressed = false;
	private RaycastHit hit;

	// Use this for initialization
	void Awake () {
		carController = GetComponent<CarController> ();
	}

	void Update () {
		if (Input.touchCount > 0) {
			Touch touch = Input.GetTouch (0);
			if (touch.phase == TouchPhase.Began) {
				Ray myRay = Camera.main.ScreenPointToRay (touch.position);
				if (Physics.Raycast (myRay.origin, myRay.direction, out hit)) {
					if (hit.collider.tag == "BrakeButton") {
						brakesArePressed = true;
					}
				}
			}
			else if (brakesArePressed &&touch.phase == TouchPhase.Ended){
				Debug.Log ("Brakes released");
				brakesArePressed = false;			
			}
		}
		if (brakesArePressed) {
			carController.ApplyBrakes ();
		}
	}
}

@ilmix123

Try limiting the distance in which you raycast. Your implementation will raycast against all colliders in the scene for an unlimited distance. Note that your variable myRay already has an origin and direction, so unless you need a specific direction to cast in, the example below should do fine.

If the time for the raycast is the issue, then below’s implementation (which sets the casting distance to 100 units) should help limiting the overhead. You can take whatever distance suits your case.

Hope this will help solving your issue.

Ray myRay = Camera.main.ScreenPointToRay (touch.position);
if(Physics.Raycast(myRay, out hit, 100))
{
    // Do your thing here
}

Regards,

Koen Matthijs

In case anyone runs into similar problem: the main cause of the lag was using Unity Remote. When running the code from regular build the lag is not there. I guess you shouldn’t rely on Unity Remote too much, especially when it comes to performance related issues.