How do I detect a touch on a GameObject?

This is the code in the script “OnTouch”:

// Update is called once per frame
    void Update () {
        foreach(Touch t in Input.touches)
        {
            Debug.Log ("We have touches!");
            Ray ray = Camera.main.ScreenPointToRay(t.position);
            RaycastHit hit;
            Debug.Log (Physics.Raycast(ray, out hit));
            if(Physics.Raycast(ray, out hit))
            {
                Debug.Log ("We have a hit!");
                switch(t.phase)
                {
                case TouchPhase.Began:
                    hit.collider.SendMessage("OnTouchDown", null, SendMessageOptions.DontRequireReceiver);
                    //hit.collider.SendMessage("OnMouseDown", null, SendMessageOptions.DontRequireReceiver);
                    //hit.collider.SendMessage("OnTouchOver", null, SendMessageOptions.DontRequireReceiver);
                    //hit.collider.SendMessage("OnMouseOver", null, SendMessageOptions.DontRequireReceiver);
                   
                    break;
                case TouchPhase.Moved:
                case TouchPhase.Stationary:
                    //hit.collider.SendMessage("OnTouchOver", null, SendMessageOptions.DontRequireReceiver);
                    //hit.collider.SendMessage("OnMouseOver", null, SendMessageOptions.DontRequireReceiver);
                    break;
                default:
                    //hit.collider.SendMessage("OnTouchUp", null, SendMessageOptions.DontRequireReceiver);
                    //hit.collider.SendMessage("OnMouseUp", null, SendMessageOptions.DontRequireReceiver);
                    break;
                }
            }
        }
    }

It is attached to the parent canvas of my objects:

But the Physics.Raycast always return false so I can’t detect anything.

What is wrong here?

Also, isn’t there an easier way to detect touches? Like adding a “Touch Component” or a “Touch Script” to a GameObject?

Best regards

Yes. If you are in 4.6 or above you can use the EventSystem. For the UI stuff this happens automatically. For non UI use the following approach

  • Add an EventSystem GameObject
  • Add a PhysicsRaycaster to your camera
  • Add a collider to you clickable object
  • Implement the appropriate event system interfaces on your clickable object. There is a list here.
3 Likes

Hi can you please elaborate on the 4th point. I’d like to try this i dont think people are using this method. I see a bunch of raycast examples only.

I believe it’s the third method in this video.

1 Like

can’t agree more