0
\$\begingroup\$

How do I raycast from a UI object? I have tried

Ray ray;
Camera cam;
Transform obj; //UI object

ray = cam.ViewportPointToRay(obj.position);

AND

ray = new Ray(obj.position, obj.forward);

Neither of these seem to work.

\$\endgroup\$
3
  • \$\begingroup\$ Not an answer but you can debug your ray if the ray is hitting correct target or not. To debug ray user "Debug.DrawRay". for documentation : docs.unity3d.com/ScriptReference/Debug.DrawRay.html \$\endgroup\$
    – Swati
    Oct 11, 2019 at 5:47
  • \$\begingroup\$ I know that. It does not work too. \$\endgroup\$ Oct 11, 2019 at 5:53
  • \$\begingroup\$ How are you using these rays, and what is the specific symptom of "not working" that you're facing? The code you've shown us so far looks perfectly correct for some purposes — if it's not doing what you want then it sounds like your purpose is something else, so tell us about that gap. Be sure to include details of your scene setup like what mode your canvas is using.— one version looks like it's written for screen-space, the other for world-space, so we need to know what you're actually trying to use it for. \$\endgroup\$
    – DMGregory
    Oct 11, 2019 at 6:04

1 Answer 1

0
\$\begingroup\$

I've figured it out:

ray = cam.ScreenPointToRay(obj.position);
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .