I'm trying to create a 3D click to move game in Unity3D.
I have added a UI Button
(using UnityEngine.UI
) that I would like to eventually click to toggle running on and off.
However, clicking on the Button
actually seems to be clicking through onto the scene (in my case NavMeshAgent
navigation) and causes my player to move to a different location.
How can I disable ray casting for clicking UI buttons or in some way have the UI capture its own events?
I've been using typical Unity3D code to get user in put in gameplay such as
if (Input.GetMouseButtonDown(0))
{
same if I try the approach
if( Input.touches.Length > 0 )
{
if ( Input.touches[0].phase == TouchPhase.Began )
{
and it seems to be the case on iOS, Android, and desktop.
It seems to be a basic problem that clicks on the UI (UnityEngine.UI.Button
etc) seem to fall through to the gameplay.
Regarding this very old question:
As a historic matter: here is the rough-and-ready quick-fix, which you used to be able to use in Unity years ago...
if (Input.GetMouseButtonDown(0)) { // doesn't really work...
if (UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())
return;
Bingo();
}
Realistically, you cannot do this any more, for some years now.
Setting aside the historic quick-fix...
Here's how you do it in Unity today:
Add a raycaster (that takes one click), and
Do this:
-
using UnityEngine.EventSystems;
public class Gameplay:MonoBehaviour, IPointerDownHandler {
public void OnPointerDown(PointerEventData eventData) {
Bingo();
}
}
Basically, again basically, that is all there is to it.
Quite simply: that is how you handle touch in Unity. That's all there is to it.
Add a raycaster, and have that code.
It looks easy, and it is easy. However, it can be complicated to do well.
(Footnote 1 - full details: Horrors of OnPointerDown versus OnBeginDrag in Unity3D )
(Footnote 2 - for historic reasons: if the link still works, here's the original famous video on how to do "new" touch in Unity, from back then: link, part 3.)
Unity's journey through touch technology has been fascinating:
"Early Unity" ... was extremely easy. Utterly useless. Didn't work at all.
"Current 'new' Unity" ... Works beautifully. Very easy, but difficult to use in an expert manner.
"Coming future Unity" ... Around 2025 they will make it BOTH actually work AND be easy to use. Don't hold your breath.
(The situation is not unlike Unity's UI system. At first the UI system was laughable. Now, it is great, but somewhat complex to use in an expert manner.)
Handy related tip!
Remember! When you have a full-screen invisible panel which holds some buttons. On the full-screen invisible panel itself, you must turn off raycasting! It's easy to forget: