I have a scene with GameObjects that can be clicked. I also have an info panel at the bottom of the screen.
This panel have a hide/show function and it works well. The problem is when the panel is active, if the player click on the panel and ther is a gameobjects behind the panel, the gameobject is also clicked, and ofc, I dont want that. I need the gameobjjects to be “not clikable” if they are behind the panel.
How i prevent the click to “reach” the gameobject if there is a panel in front?
Maybe raycast is the solution? I’ve never used it… some another way to do it?
void Update()
{
// Check if the left mouse button was clicked
if (Input.GetMouseButtonDown(0))
{
// Check if the mouse was clicked over a UI element
if (EventSystem.current.IsPointerOverGameObject())
{
Debug.Log(“Clicked on the UI”);
}
}
}
I don’t recommend checking for and analyzing mouse clicks in Game Objects’ Update(). All objects that have the script are going to be checking and analyzing mouse clicks every single frame. That isn’t a good practice and will quickly cause performance problems. There are different callbacks for input events that you can use.
Your clicks won’t be registered through other objects.
If you use these, you only need to make sure that your panel is a Raycast Target (it is by default), and it’s going to block out the Raycast from these callbacks. They also work better on touch screens than OnMouse callbacks.
(Clickable objects are always Raycast Targets. Others you might set just to block raycasts when over something.)
If you have something like this on your Game Objects, it won’t be fired if a button, or panel, or anything else was clicked while your Game Object is behind:
using UnityEngine;
using UnityEngine.EventSystems;
public class TouchForceExample : MonoBehaviour, IPointerClickHandler {
public void OnPointerClick(PointerEventData data) {
// This will only execute if the objects collider was the first hit by the click's raycast
Debug.Log(gameObject.name + ": I was clicked!");
}
}
Another Example:
using UnityEngine;
using UnityEngine.EventSystems;
public class TouchForceExample : MonoBehaviour, IPointerUpHandler, IPointerDownHandler {
public void OnPointerDown (PointerEventData data) {
ExamplePhysicsScript.instance.ForceIncrement ();
}
public void OnPointerUp (PointerEventData data) {
ExamplePhysicsScript.instance.ForceSet ();
}
}
You can also use PointerEventData in interesting ways. For example to track the position of the pointer while it’s down (so the user can drag something), or just to get a vector from pointer down to pointer up with PointerEventData.position.
I realise this is an old thread - but I just found a simple solution: I made a transparent panel the size of the UI canvas. I arrange for everything I want to mask to be above it in the hierarchy and everything I don’t to be below (a popup input dialogue for example). So when I call up the input dialogue I also enable the transparent panel. Job done!