How can I disable the method if there is a UI on top of the object?

24 views Asked by At

The code below is triggered when the player clicks on the mouse button, if there was an object under the mouse, then the object changes its material

private void Update()
{
       if (ClickCheck(out var hit) && hit.transform.TryGetComponent(out Script script))
       {
               script.MaterialSet(newMaterial); 
               // New material 
       } 
}

private void ClickCheck(out RaycastHit hit) 
{
      if (Input. GetMouseButtonDown(0)) 
      {
             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 
             
             if (Physics.Raycast(ray,  out var hit)) return true; 

             hit = new RaycastHit(); 
             return false; 
      }
} 

How do I make it so that when clicking on the UI, the Click Check method does not work?

I tried to do a check inside ClickCheck via EventSystem.current.IsPointerOverGameObject, but for some reason the check didn't work. This example looked like this

private void ClickCheck(out RaycastHit hit) 
{
      bool b = EventSystem.current.IsPointerOverGameObject; 

      if (Input. GetMouseButtonDown(0) && d == false) 
      {
             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 
             
             if (Physics.Raycast(ray,  out var hit)) return true; 

             hit = new RaycastHit(); 
             return false; 
      }
} 

I have another option to make a beam that will check UI objects. But adding a Collider to each UI object is too difficult, because there are so many of them.

0

There are 0 answers