Using RayCast to see if button clicked

I get the button using this:

Button button = GameObject.FindGameObjectWithTag("MainCanvas").GetComponentInChildren<Button>();

And then I do:

void Update()
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;
    if (Physics.Raycast(ray, hit))
    {
            if (button.collider.Raycast(mainCamera.ScreenPointToRay(Input.mousePosition), hit))
{ //Code to run when button clicked
    }
 }
 }

However I keep getting errors on this. Any idea where i’ve gone wrong? Thanks

Normally you do:

if(Physics.Raycast(ray,out hit,rayLength))
{
	if(hit.collider.tag == "button")
	{
    //do what ever
    }
}

If you tag the button , you dont need to get the component from somewhere, basicly. Or you try:

if(Physics.Raycast(ray,out hit,rayLength))
{
	if(hit.collider.gameObject == button)
	{
    //do what ever
    }
}

Maybe it helps. Cheers

Edit: Don’t forget to add a collider to your button :wink: