Search Unity

Check what a raycast passes through.

Discussion in '2D' started by aaroshdas, Jan 18, 2022.

  1. aaroshdas

    aaroshdas

    Joined:
    Apr 6, 2020
    Posts:
    29
    How would I go about checking all the things a raycast passes through. Currently my code
    Code (CSharp):
    1.         RaycastHit2D hit =   Physics2D.Raycast(transform. position, direction);
    How would I go about storing all the things the raycast hits. For example, if there were 2 boxes the ray cast passed through, it would store the information of both boxes?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    You want
    RaycastAll
    .
     
  3. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,459
    As above but know that the "All" suffixes, whilst convenient, create an array and so afterwards you are leaving an array to the garbage collector which can lead to poor performance and visual jitters whilst the GC runs if you do it too much.

    There's overloads to all physics queries including Raycast that allow you to provide an Array or List where the results will go. Reusing this means you never produce garbage to be collected and so it improves performance.

    In short, any physics query, try not to use any with a suffix of "NonAlloc" or "All". When you start though, they are very convenient to use. :)

    HINT: The API docs show you this so just browse them. Look at Raycast above and scroll down, it shows you what you can pass it to.