Reputation: 153
All my game is made by UI. I have some function called when i press left mouse button. But it also react for UI button clicks, so i want to check if i click on UI element or not, and than decide what to do. I found that
EventSystem.IsPointerOverGameObject()
can help, but, as i said - all my game made of UI elements, so, if i use it - i cant do anything in scene. Is there a way to point which exactly elements shoul it ignore? Buttons for example. Or is there a way to call Input.GetMouseButton(0)
only for certain layer?
Upvotes: 1
Views: 1580
Reputation: 469
Adapted from https://docs.unity3d.com/2019.1/Documentation/ScriptReference/UI.GraphicRaycaster.Raycast.html
put your buttons and anything else that you don't want to call your function in a separate layer
public LayerMask clickable;//exclude the button layers here
GraphicRaycaster m_Raycaster;
PointerEventData m_PointerEventData;
EventSystem m_EventSystem;
void Awake(){
m_Raycaster = GameObject.FindObjectOfType<GraphicRaycaster>();
m_EventSystem = GameObject.FindObjectOfType<EventSystem>();
}
void Update(){
if (Input.GetKey(KeyCode.Mouse0))
{
//Set up the new Pointer Event
m_PointerEventData = new PointerEventData(m_EventSystem);
//Set the Pointer Event Position to that of the mouse position
m_PointerEventData.position = Input.mousePosition;
//Create a list of Raycast Results
List<RaycastResult> results = new List<RaycastResult>();
//Raycast using the Graphics Raycaster and mouse click position
m_Raycaster.Raycast(m_PointerEventData, results);
foreach (RaycastResult result in results)
{
//is the layer of the gameObject hit included in clickable?
if(clickable == (clickable | (1 << result.gameObject.layer))) {
doYourFunction();
break;
}
}
}
}
Upvotes: 1