So i want this problem with ui buttons done

So I have a few UI buttons. But I also have a script which refers to a ray and raycast and removes the buttons if nothing is clicked on or changes the buttons which are displayed depending on what gameobject is clicked on. My problem is that when I try to click on a button, Unity interprets it as not clicking on anything and removes the buttons, so nothing ever gets done. Ideally, I want the code to look something like this

if (Input.GetMouseButtonDown (0)) {
<If there isn’t an interaction with a UI button>
if (Physics.Raycast (ray, Mathf.Infinity)) {
if (hit.transform.gameObject.tag == “Tile”)
//do a thing

How do I set this sort of process up or what should I refer to? Ive looked around and can’t find a proper answer or it’s explained in a way I don’t really understand. Thank you in advance.

check with EventSystem.current.currentSelectedGameobject before raycasting. If your code is executed prior to the Unity Eventsystem, change its execution order to execute later.