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?

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 :wink:

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