Hi,
I have some gameobjects that can be selected by click mouse, but they are been selected even if I click on my GUI (if the GUI is over the gameobject on screen)
There’s any way to avoid mouse clicks over UI of interact with the gameobjects?
Whoa! I was trying something with the EventSystem right now!
It’s exactly this that I needed.
As each selectable 3D game object has a script that implement the OnClick() method, when is clicked something happens.
I made
void OnClick()
{
if (!EventSystem.current.IsPointerOverGameObject())
//do something
}
You probably don’t need this but after some testing and tweaking I handle it with this bit of code where I use the event system to catch the UI hits (and therefore block raycasts) and if no UI was hit then go on and do the raycast instead:
public class MouseClickTest : MonoBehaviour {
public EventSystem eventSystem;
public Camera orthoCamera;
void Update () {
if (Input.GetMouseButton(0)) {
if (eventSystem.IsPointerOverGameObject()){
// No code needed here your UI elements will receive this hit and NOT do raycast info in the else below
} else {
Ray ray = orthoCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit)) {
// if you got a valid hit with the ray then do something with it here
}
}
}
}
}
I got it @melkior . Thanks!
I did the selection by click using raycast before, but as each of my objects are dynamically created, I prefered put a script on each one doing implementation of OnClick() and delegating for Unity the work of specify when the mouse was clicked over which object (because will activate its OnClick()).
But I imagine that the OnClick() method shall encapsulate some logic like your Raycast approach that you made above (same as I did on the past). Am I right?
Hi there,
I stumbled upon your post because I’m trying to make so that my physics raycast is blocked by the GUI but I’m trying to solve this with touch input, sadly the following code isn’t working:
Nubeh - I have not tested this with Touch input at all - its possible something else is needed in this context unfortunately I am not working on mobile titles so its outside of my current experience/knowledge.ts
Here’s the solution I came up with for mobile. I set the GraphicRaycaster in the inspector from my one canvas item I have in my scene. Whatever code you put in the designated spot will only register if you are not pressing on a UI element.
using UnityEngine.EventSystems;
Vector2 touchPos;
public GraphicRaycaster GR;
void Update()
{
if(Input.touchCount > 0)
{
if(Input.GetTouch(0).phase == TouchPhase.Began)
{
PointerEventData ped = new PointerEventData(null);
ped.position = Input.GetTouch(0).position;
List<RaycastResult> results = new List<RaycastResult>();
GR.Raycast(ped, results);
if(results.Count == 0)
{
// YOUR CODE HERE
}
}
}
}