0
\$\begingroup\$

I have a grid of gameobjects with colliders. Currently they all have unity's inbuilt void OnMouseDown function which gets called when the mouse clicks on a collider. This then executes some game logic on the gameobject.

I realise that I could instead use a seperate script to send a raycast when the player clicks and if it intersects with one of the afformentioned gameobjects I can execute the code that way.

Is one approach better than the other? Or behind the scenes is unity using the raycast method for void OnMouseDown anyway? (Or is there perhaps a non-performance reason why you'd use one approach rather than the other)

Thank you.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Behind OnMouseDown, Unity is transforming your mouse position from window coordinates to view coordinates, projecting into the world using the view-projection transform and testing this ray against Colliders that have the right "layer mask" for OnMouseDown receivers.

You should be able to see what it actually calls to do this in the profiler. It's probably just exactly would want to do if you are using Colliders or Unity's physics module more generally. IIRC it uses RayCast.

A motivation for doing it yourself would be that you can specify a layer mask when calling RayCast, so that fewer Colliders are tested, which could benefit performance.

Another motivation could be that you want to take control of when exactly the ray tests happen, rather than supply a callback to an opaque system, whether for performance or just preference.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Thank you, exactly what I was looking for. That last part about layermasks is spot on for me, although I don't think I need a layermask now it's entirely possible I could later on in development. \$\endgroup\$ Commented Jan 24, 2023 at 9:54
  • \$\begingroup\$ Yes, I wouldn't bother about it unless you find a need to for some reason. If the profiler says your spending a lot of time checking rays from mouse clicks, I'd sanity check the collision layers before writing any code. \$\endgroup\$
    – hazeycode
    Commented Jan 24, 2023 at 10:04
  • \$\begingroup\$ I added another possibly reason to DIY to my answer. \$\endgroup\$
    – hazeycode
    Commented Jan 24, 2023 at 10:18

You must log in to answer this question.

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