In my 2D game, the user can draw lines by touching and dragging on the screen. The problem is that lines also get drawn when the user simply clicks on UI buttons. How can I prevent that?
If you have an event system in the scene, you can use:
EventSystem.current.IsPointerOverGameObject()
Note: If you have a physics or physics2d raycaster, as well as a graphics raycaster(for the UI), then you may want to raycast from the mouse position to see if you hit a button, instead. That’s because clicking objects with colliders would also return true for the Pointer Over game object, in that case.
Thank you. How could I raycast from the input position and check if it has touch a button? Sorry for the bother, but I am fairly new to Unity
Try this, from the docs: https://docs.unity3d.com/ScriptReference/UI.GraphicRaycaster.Raycast.html
I think, if it were me, I’d first try the IsPointerOverGameObject() check, and then only if that’s true would I raycast, and then check if it’s something you want to block the raycast (or just anything, if you want everything to mean "don’t draw while over this UI ").
Remember, though, if you don’t have a physics or physics2D raycaster in your game, you can use the IsPointerOverGameObject and not worry (… unless there are some UI elements you can be over and still draw lol).
Thank you very much! Unfortunately, I do have physics 2D in my game, so I can’t just use the simple version. I’ll try the version where you check if the ray touches an UI element and block it
Okay, and just to double-check … do you have a physics2D raycaster in the scene? – that is the the deciding factor, not just using physics 2D (in case you thought that, I don’t know).
K, hope the raycast works if you try that. report back either way to say how it went. =)
Success! It works like a charm with just IsPointerOverGameObject()! I didn’t know what Physics2D Raycaster was, so I assumed you meant Physics2D, but after some documentations, I figured it out. Thanks for the help!
No problem Glad it’s working for you.