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?
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:
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.
So the best thing is to adjust the z value based on which Gameobject to hit first