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

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

ray = cam.ViewportPointToRay(obj.position);


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

Neither of these seem to work.

  • \$\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 '19 at 5:47
  • \$\begingroup\$ I know that. It does not work too. \$\endgroup\$
    – MetaMax
    Oct 11 '19 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 '19 at 6:04

I've figured it out:

ray = cam.ScreenPointToRay(obj.position);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.