Clicks are detected through the UI elements

I have a scene with some 2D objects with colliders that detect clicks (OnMouseUpAsButton). I just have added a button and it seems to work (it changes its color when clicked, etc), but when the button is over one of the aforementionend 2D colliders, the click is detected by both elements.

How can this be avoided? That is, I want the click to be detected only by the element which is over; namely, the button.

For a sort of quick fix you can make a global variable.

class Menu
public static bool GuiClick;

void OnGui(){
GuiClick = false;

if(button) GuiClick = true;

void Update(){
if(Menu.GuiClick) return;

//Game stuff

This isn’t tested, as the Gui will run at a different speed than Update, but it’s worth a shot.

I have not tested this yet, but maybe you could use the IsPointerOverGameObject function. I think your 2D colliders will work with an input system different from the UI EventSystem, and before you take actions on them you can check if the EventSystem is registering input on some UI element.