- Home /
Detect canvas object under mouse because only some canvases should block mouse.
Here is what I am trying to do: I have say 6 canvases, where 1 is an overlay HUD, but the remaining canvases are informational health bar type canvases. I want to prevent mouse actions when mouse (or touch) is over the HUD but not over the other canvases.
So this question doesn't cover it because it references EventSystem.current.IsPointerOverGameObject which only tells me it's over some canvas object. But I need to know if its over a specific object.
What I'd like to do is get a reference to the canvas object under the mouse, like UEventSystem.current.GameObjectUnderPointer and then use compare tag.
I can't seem to do it with a raycast, presumabely because I can't get the canvas camera, but even then I sometimes have world canvases I will want to prevent touches on.
I am not sure how to proceed and am looking for advice. Thanks!
I can't tell whether this will help or not, but just in case...
http://docs.unity3d.com/$$anonymous$$anual/class-CanvasGroup.html
Answer by taiku · Jul 19, 2015 at 05:08 PM
So I figured this out myself, with one catch. There is a method in the EventSystem called RaycastAll which does exactly what I was looking for. It casts a raycast into the event system and returns canvas objects in the raycast (code below).
This works to get all the canvas elements under mouse, but when I enable my canvas background image (the one that has the ignore tag) it intercepts events from all the other canvas elements. I can't add the canvas group and disable "blocks raycasts" or it kills my raycast code below. So to solve this I simply created 2 canvases and moved the second one behind the first one and am putting all of my background images in that one. But this ruins my hierarchy and a simple priority or respecting the items z-position would solve this (in Unity's internal event system). So this is annoying. (Edit: I realized you can put the image higher in the hierarchy and then children receive events first, but this is still an annoying way to do it, hierarchy should be for organization IMO and a simply priority would be easy to add).
Event System Raycast Code:
public List<RaycastResult> RaycastMouse(){
PointerEventData pointerData = new PointerEventData (EventSystem.current)
{
pointerId = -1,
};
pointerData.position = Input.mousePosition;
List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(pointerData, results);
Debug.Log( results.Count);
return results;
}
Your answer
Follow this Question
Related Questions
I can't use more that two buttons at the time. How do I change that? 0 Answers
Touch to Ray on Canvas 1 Answer
How to get PointerEventDatas[]? 0 Answers
My Canvas only accept 2 touchs at same time 0 Answers
Check UI panel touched after OnEnable()? 0 Answers