- Home /
How to prevent raycast when clicking 4.6 UI?
I have it so I can click enemies to target them and if the player clicks anything else it clears the target but if I want to then click my spell icon to cast a spell it will detect terrain or whatever is under the UI object and reset my target.
How can I prevent this?
Answer by troien · Nov 02, 2014 at 11:31 AM
You could check for the following to be false before you do your own raycast.
UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()
If this value is true, you should be hovering any of your UI elements, if false not.
On a sidenote, If you use a CanvasGroup component to hide your menu, make sure you also uncheck the 'Blocks Raycast' when you hide it. (otherise Unity will tell yo that you are hovering the invisible UI ;)
@troien - do you happen to know of the link in the scripting guide to this function please? $$anonymous$$y system says that function does not exist. I looked in the scripting pages and could not find it listed either. The best I could find was this (http://docs.unity3d.com/460/Documentation/ScriptReference/EventSystems.EventSystem.html) which is obviously not right
Nope, I can´t. The Unity scripting reference is not up to date, and does not contain this. However, the autocomplete of visual studio/monodevelop tells me this method exists and this method works for me. Which version of Unity are you currently using? (I'm using 4.6.0b20)
This worked.
After a little searching you want to add -1 to check for mouse.
UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject(-1)
$$anonymous$$y version is 4.5.0f6. Ah, a new feature, all is well - I'd assumed that I'd made some import mistake. I've now found the beta script guide link, but it still does not have the function - but as you say, its not up to date. Thanks for reply :)
Answer by Kiwasi · Dec 26, 2014 at 04:33 AM
Also worth noting that you can abandon your own ray casting solution and use the Unity event system with a physics raycaster. You can them implement the various interfaces from UnityEngine.EventsSystem.
Note that the event system is also intended to replace SendMessage.
Edit: Adding a YouTube video, since this question has been asked a few times
hi, looks nice but I'm confused, what if i have a Gamemanager that handle a start game click (basicly any key on any spot on the screen). where do i need to implement the interface then (i've tried to implement it on that Game$$anonymous$$anager but no luck, the OnClick function doesnt fire at all). thanks in advanced
What a comprehensive answer the youtube video is. Thank you for sharing this!