How to raycast against uGUI objects from an arbitrary screen/canvas position

We wanted to do a raycast from an arbitrary position over uGUI objects. As far as we can tell, we seem to need an instance of GraphicRaycaster. One comes attached to the default Canvas, so we can easily get its reference (let’s call it “raycaster”) and then call raycaster.Raycast(…).

Now, Raycast receives two arguments: a PointerEventData and a List. Currently, the documentation for Raycast does not describe what it does exactly, but we assume that the List of RaycastResults is filled by Raycast itself. From each RaycastResult we could then access the gameObject it hit (documented here).

But what about PointerEventData? Isn’t it supposed to come from a pointer event? Here, we have no mouse or touch, and simply want to raycast from an arbitrary position. How should we proceed to create one and set its (screen/world) position? Or is there another way for uGUI raycasts altogether?

So you are correct on the List. It is the that get appended to with every hit. The PointerEventData is prepopulated by the EventSystem with the mouse/ touch positioning information. Its the only data that is looked at and is used to determine where the say is cast from.

OK, thanks for confirming the info :slight_smile:

The main issue is that we don’t know how to proceed if we want to create a raycast from any screen position because, as you mentioned, PointerEventData is created by the EventSystem, from mouse and touch events.

Details: we have large objects in the scene, which have colliders. We drag those objects using OnMouse events, and want to be able to release them over uGUI elements. The objects are large, so the user might drag them by their borders and not their center position. This means that relying on hover is out of the question (most of the object might already be inside the uGUI release area, but the pointer is still outside).

This is why we want to do a raycast using the dragged object’s center position (not the pointer position). Is this possible?

For people also looking for this, I ended up finding how to do it (it was not so hard) and answered myself at this post at Unity Answers, so please check a possible solution there.