Search Unity

Does sorting layer affect the way raycast hit on the gameobjects?

Discussion in 'Scripting' started by zyonneo, Sep 17, 2019.

  1. zyonneo

    zyonneo

    Joined:
    Apr 13, 2018
    Posts:
    386
    Consider A,B,C game objects with default sorting layer with layer order A=-3,B=-2,C=-1.So if A,B,C are on top of each other then the ray should hit C first.Right?When I did a example it did not happen? Does the sorting layer have any effect on ray hitting game objects?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,674
    GameObjects don't have sorting layers. Renderers and other things that produce visual output may have a Sorting order that is unrelated to and uninvolved in what Physics.Raycast uses.

    GameObjects have a Layer, which you can optionally use to have Raycast exclude or include specific things it hits, IF you use the version of Raycast that takes LayerMask argument.

    Physics.Raycast doesn't actually hit GameObjects either: it hits some kind of collider on a GameObject.

    The Physics.Raycast API says nothing about which collider it returns if it can hit more than one:

    https://docs.unity3d.com/ScriptReference/Physics.Raycast.html

    You might want to apply layers to the objects to differentiate them, or use RaycastAll and use your own mechanism for determining what you hit and what you want to hit, unless somebody here can suggest another way.
     
    letuantam96 and zyonneo like this.
  3. zyonneo

    zyonneo

    Joined:
    Apr 13, 2018
    Posts:
    386
    So the best thing is to adjust the z value based on which Gameobject to hit first
     
    pedroarruda4991 and letuantam96 like this.