Raycast malfunctions on loaded prefabs

Hi Everyone,

So I have a 2D scene with buttons. When I click on a button a sprite prefab is instantiated from resources and you drag it on a roster (squarefield sprite) based on your mouse coordinates. When I click on an object in the roster it gets recognized by its tagname and is selected. However, when I instantiate a few more prefabs like 5 in total all of a sudden some objects on the roster wont get selected anymore. The reason is the raycast doesnt detect the tagname anymore but instead in the debugger the roster’s tagname is detected.

The order in layer of the roster is 0 and the order in layer of the loaded prefab sprites is 4 so the ray should be able to detect the instantiated object tagname when I click on the object with the mouse but instead some objects wont be recognized anymore.

Does anyone have any idea what could be wrong ?

  RaycastHit2DrayHit2=Physics2D.GetRayIntersection(Camera.main.ScreenPointToRay(Input.mousePosition),100);
Debug.Log("objecthit: "+ rayHit.rigidbody.gameObject.tag);
if (rayHit2.rigidbody.gameObject.tag==BuildingFieldT)
{ //when 5+ prefabs are loaded sometimes this command wont be executed anymore
   //because it wont detect my prefab's BuildingFieldT tag even when my mouse is on the prefab object.

Hello there, so I do not see anywhere and exact confirmation of this, but I think rays are not affected by sprite rendering order. I am not sure that by 0 layer you are referring to the sprite sorting layer, or the actual layers (both can be founded in Tag Manager). Usual rays stop on the first object that is detected on the trajectory. You should use layer mask and remove the possibility that the roster is detected.

The best way to use layer masks is to create a public LayerMask property, edit it from inspector by selecting unwanted layer, and feed it into the raycast function.
You will have to set different layers for the roaster and sprites.

Plase note that I am talking about actual Layers, not Sorting Layers.

Thanks so much. The layermask did the trick.

Cheers !