Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

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

Discussion in 'Editor & General Support' started by laserDogRob, Oct 16, 2021.

  1. laserDogRob

    laserDogRob

    Joined:
    Jun 20, 2018
    Posts:
    39
    Hey,

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

    Code (CSharp):
    1. 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!
     
  2. laserDogRob

    laserDogRob

    Joined:
    Jun 20, 2018
    Posts:
    39
    (I'm using "RaycastNonAlloc" btw, to save on GC)
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,756
    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://forum.unity.com/threads/is-...ng-square-roots-in-2021.1111063/#post-7148770

    Notes on optimizing UnityEngine.UI setups:

    https://forum.unity.com/threads/how...form-data-into-an-array.1134520/#post-7289413
     
  4. laserDogRob

    laserDogRob

    Joined:
    Jun 20, 2018
    Posts:
    39
    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.