Touch detect game object

Hello,
I want my code to detect a single game object on touch.
This is my current code

 void Update()
    {
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
        {
            RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint((Input.GetTouch(0).position)), Vector2.zero);
            if (hit.collider != null )
            {
                Debug.Log("touch bird");
            }
        }


    }

when i touch anywhere on the screen the debug fires.
How can I get it so its just the game object.
Thank you.

1 Like

It depends on the type of object, but this is the most generic, easy way to do it:

If that doesn’t work for u please let us know what kind of object you want, 2d, 3d, UI?

Im using 2D currently, I used OnMouseDown prior but it only registers one touch at a time and has a high latency, so I need a new option.
Thank you.

It will also depend on what kind of behavior you want, do you want objects for themselves to know when they are clicked on? If so then you can use this to detect continuous click
https://docs.unity3d.com/ScriptReference/EventSystems.IPointerDownHandler.html
or this to detect single click release
https://docs.unity3d.com/ScriptReference/EventSystems.IPointerClickHandler.html

But if you want a foreign object to observe others than you can continue using your original raycast script and check if they have a specific tag on them, this is one example you can use:

In your code you use if (hit.collider != null ) so, you’d just replace with a specific test. You can even check for specific instances of an object, and not tag exactly.

I tried pointerdownhandler and pointerclickhandler and untiy will intercept my events but my function wouldn’t fire, I now have a new object detecting collision with the original object I want to touch.

  private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "bird")
        {
            if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
            {
                RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint((Input.GetTouch(0).position)), Vector2.zero);
                if (hit.collider != null)
                {
                    GetComponent<BirdBounce>().Jumpies();
                }
            }
        }
    }

This is my code now and im getting a null reference exception. No idea what to do. I even tried event triggers.

Post us the error stack.

I kept coding last night, I no longer get an error but it does not detect touch.