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;
}
}
}
}
}