Raycasting in new GUI

So I’m a little confused exactly how to implement Rays in the new GUI.

  1. If I’m using a ScreenSpace Overlay canvas, what sort of Physics am I using to detect hits on different objects on the panel, 2D or 3D? Could you provide an example of a code used to detect such a hit?

  2. Do I need to add another camera or can I attach the script to the main camera?

  3. Do I need a 2D or 3D box collider on my gameobjects?

+anything other information that may be relevant, thanks!

Generally speaking, to raycast against uGUI objects you can do like I did here. Just notice that my example requires camera.WorldToScreenPoint, because my Canvas is in World Space and I had a world position, but, to raycast, we require a screen position. We’ll get there in a moment.

To answer your questions:

  1. You shouldn’t need the Physics class for uGUI objects, whatever Canvas mode you’re using. An object can be hit by EventSystem.current.RaycastAll(pointerEventData, raycastResults) when it has a component that is a possible target of the configured raycasters (see the link I gave you for more code). For example, a Canvas has a GraphicRaycaster attached by default, which allows EventSystem.current.RaycastAll to hit uGUI elements that are Graphics (Image, Text, etc). PhysicsRaycaster is another raycaster that allows raycasts against colliders (there are two: PhysicsRaycaster and Physics2DRaycaster) and requires a Camera.

  2. You can put the script that raycasts anywhere. uGUI Raycasts use 2D (screen) positions. If you already know the 2D position to cast the ray from, ignore what I’m about to say.

If you have a 3D (world) position and your canvas is in a mode that uses a camera, you’ll likely need to convert the world position into a screen position (to then raycast from there). Again, the code in my link does that :slight_smile: If - as is your case - your Canvas is in Overlay mode, world positions (discarding Z) already correspond to screen positions, so you shouldn’t need the conversion. Unless I’m mistaken. If I am, try using the InverseTransformPoint method of RectTransform to convert them. Use it like canvasRectTransform.InverseTransformPoint(someWorldPosition).

  1. Colliders are required for the Physics’ Raycast methods (either 2D or 3D) and for the PhysicsRaycaster, when used as as one of the possible raycasters in the EventSystem. However, if you simply want to raycast against Graphic uGUI objects, you don’t need colliders and can rely on the GraphicRaycaster. :slight_smile:

Many thanks to Xtro for correcting me, as I didn’t know about the PhysicsRaycaster and was spreading misinformation. I modified a great deal of this answer, so please correct me if needed or edit my answer (I changed it to community-editable).

@cansilLupus, that’s the best thing i have ever learned on community thank you very much be blessed