How to detect touch on a game object

Ashish Beuwria picture Ashish Beuwria · Jan 28, 2014 · Viewed 24.6k times · Source

I'm developing a game on Unity for iOS devices. I've implemented the following code for touch:

void Update () {
    ApplyForce ();
}

void ApplyForce() {

    if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began) {
        Debug.Log("Touch Occured");     
    }
}

I've dragged this script onto my game object which is a sphere. But the log message appears no matter where I touch. I want to detect touch only when the users touches the object.

Answer

Steven Mills picture Steven Mills · Jan 28, 2014

stick the code bellow in your camera, or something else that will persist in the level you're designing. It can be anything, even an empty gameobject. The only important thing is that it only exists ONCE in your level, otherwise you'll have multiple touch checks running at the same time, which will cause some seriously heavy load on the system.

void Update () {
    if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began) 
    {
        Ray ray = Camera.main.ScreenPointToRay( Input.GetTouch(0).position );
        RaycastHit hit;

        if ( Physics.Raycast(ray, out hit) && hit.transform.gameObject.Name == "myGameObjectName")
        {
            hit.GetComponent<TouchObjectScript>().ApplyForce();  
        }
    }
}

In the above script, hit.transform.gameObject.Name == "myGameObjectName" can be replaced by any other method you want to check that the object hit by the raycast is the object you want to apply a force to. One easy method is by Tags for example.

Another thing to keep in mind is that raycast will originate at your camera (at the position relative to your finger's touch) and hit the first object with a collider. So if your object is hidden behind something else, you won't be able to touch it.

Also put the script bellow in your touch object (in this example, called TouchObjectScript.cs)

void Update () {
}

public void ApplyForce() {

        Debug.Log("Touch Occured");   
}

If something wasn't clear, or you need any further help, leave a comment and I'll get back to you.