Help with Layermasks

Im making a RTS game where you can buy buildings and click to place them. I have a OnMouseDown function on the building which makes a GUI open containing different units from that building but I have a problem. When the GUI to buy and place the building intersects another building that has been placed it buys the building to be placed and it fires the OnMouseDown function too. (See the picture its easier to understand). I’ve tried using a layer mask and that may be the answer but it didn’t work correctly so I must be doing something wrong.

Basically I want anything with the Layermask “Button” to be in front of every other layer so a raycast doesn’t go through it and trigger anything behind it

Thanks for the help!!
Heres the layermask code:

public Layermask Button;


 void OnMouseDown()
    	{
    		
    		RaycastHit hit;
    		Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    		
    if (Physics.Raycast (ray, out hit, Mathf.Infinity, Button)) {
    
    			print ("Hit");
    		
    		}

There are many duplicate questions/answers on this topic; please search “Unity UI click through” for a sampling. Here’s one that has a vid link