Mouse Click is passing the GUI

Hi!
I wrote a simple script which is selecting the GameObject clicked by Mouse:

public static GameObject SelectedGameObject()
    {
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit, 10f))
        {
            if (hit.transform.gameObject.tag != "Player" && hit.transform.gameObject.tag != "ItemDatabase" && hit.transform.gameObject.tag != "Coller")
            {
                //return hit.transform.gameObject;
                if (hit.transform.gameObject != null)
                {
                    selected = hit.transform.gameObject;
                    QuickMenu.Initialized = false;
                    return selected;  
                }
                else
                {
                    QuickMenu.Initialized = false;
                    return selected;    
                }
              
            }
            if(hit.transform.gameObject == null)
            {
                return null;
            }
              
        }
            return null;
    }

The problem is when I’m clicking on the GUIControls when the GameObject is behind my GUI.My script is selecting the GameObject behind the GUI but I don’t want this result.

You can use UnityEngine.EventSystems together with EventSystem.current.IsPointerOverGameObject() and have a bool to decide wither you were on top of a UI element or not like this,

if (EventSystem.current.IsPointerOverGameObject())
                    {
                        wasOverUI = true;
                    }

You can couple this with a Canvas Group to decide which UI element is interactable or not.

@Tamerqarrain
I’m using OnGUI