Cheaper way of testing for component in raycast (2d) other than TryGetComponent?

Hey,

So, I have a shotgun that, let’s say, does 12 ray casts in one frame. Each “hit” is tested like so:

if (!hit.transform.TryGetComponent<IHittable>(out var hittable)) continue;

Seems excessive, but I’m not sure how else to go about it.

So, if each ray collides with 3 colliders, that’s 36 “TryGetComponents” in a single frame. Not ideal.

Any ideas?

Thanks!

(I’m using “RaycastNonAlloc” btw, to save on GC)

DO NOT OPTIMIZE CODE JUST BECAUSE… If you don’t have a problem, DO NOT OPTIMIZE!

If you DO have a problem, always start by using the profiler:

Window → Analysis → Profiler

Failure to use the profiler means you’re just guessing, making a mess of your code for no good reason.

https://discussions.unity.com/t/841163/2

Notes on optimizing UnityEngine.UI setups:

https://discussions.unity.com/t/846847/2

Thanks! I am currently deep into profiler and was just looking through this class and thought “this is probably very expensive!”. Just wondered if I’m doing something wrong.

There’s plenty of non-pooled objects being instantiated at the same time, that’s what I’m working on right now. Pool objects early! Im going to paint that on the wall so I don’t forget.