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

(Help)How can i detect how many raycasts are hitting an object?

Discussion in 'Scripting' started by unity_r2v1aj4JBgxfDg, Feb 15, 2021.

  1. unity_r2v1aj4JBgxfDg

    unity_r2v1aj4JBgxfDg

    Joined:
    Sep 16, 2020
    Posts:
    4
    (Help)How can i detect how many raycasts are hitting an object?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,089
    In 3D you are given a boolean back from the Raycast.

    In 2D you are given a RaycastHit2D object back and check if its collider is non-null.

    Both of these concepts are covered explicitly with sample code in the Unity documentation for Physics.Raycast and Physics2D.Raycast.

    Beware that there is no direct interoperability between 2D and 3D physics.
     
    unity_r2v1aj4JBgxfDg likes this.
  3. unity_r2v1aj4JBgxfDg

    unity_r2v1aj4JBgxfDg

    Joined:
    Sep 16, 2020
    Posts:
    4
    I am using 3d but i need the see if raycasts are hitting a specific object i looked at the documentations but there were only one bool that was to see if it hits any objects sorry i didnt specify the question enough.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,089
    There are many types of 3D raycasts.

    One is the generic Physics one: hits anything in the scene

    Another is one that lives on a collider.

    If you know which collider you care about, you can use that collider instance to see if a ray hits it.

    That way you not only know that it hit, but because you are already asking "Did anything hit this collider?" you also know what collider it is.

    These are some of the types of 3D raycasts:

    https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
    - asks "did I hit anything in the scene?"

    https://docs.unity3d.com/ScriptReference/Collider.Raycast.html
    - asks "did I hit this specific collider?"

    https://docs.unity3d.com/ScriptReference/Plane.Raycast.html
    - asks "did I hit this plane?"

    They are unrelated to each other but related conceptually.
     
  5. scr33ner

    scr33ner

    Joined:
    May 15, 2012
    Posts:
    187
    thanks will review