RayCast2Dhit Best Practices for clicking object?

I have written code that handles clicking on an object and then handles displaying some information based on the object that was clicked in a canvas and hides the canvas if nothing is clicked (example below).

My concern is that this script is running on each individual object’s update method and fires on all on of them whenever any object is clicked and has some if statements to handle displaying the correct information which might cause some processing issues if there are numerous objects.

Is there a way to implement something like this on the camera to detect the hit so I’m only running one instance of this script? Will this cause performance issues or am I just overthinking?

 void Update()
    {
        {
            if (Input.GetMouseButtonDown(0))
            {
                Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                Vector2 mousePos2D = new Vector2(mousePos.x, mousePos.y);

                RaycastHit2D hit = Physics2D.Raycast(mousePos2D, Vector2.zero);
                if (hit.collider != null && object.uniqueid != null)
                {
                    if (hit.collider.gameObject.name == gameObject.name)
                    {
                        text.text = object.Description;
                        canvas.enabled = true;
                    }
                }
                else
                {
                    canvas.enabled = false;
                }
            }
        }
    }
}

Yes, the correct way to do this would be to just listen for clicks in one place and raycast out. Set your clickable objects tag to clickable or you can use layers and raycast against them.


If you use layers, you can Raycast against only the clickable objects and if you make the hit, then do something with the hit object.


I can’t say it better than the documentation: