Raycast not working on Android but working in Editor


I have a problem with a Raycast, it works fine in the editor but when building to android, the Ray never hits at all. I’ve tried using RaycastAll(), but it doesn’t seem to hit anything at all. Same for Linecast().

Here’s the sample code :

if (Input.GetMouseButtonDown(0) || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began))
    Debug.Log("Mouse button accepted");
    Ray ray;
    // if touchscreen
    if (Input.touchCount > 0 && Application.isMobilePlatform) 
        Debug.Log("Ray set for mobile");
        ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
        Debug.Log($"Mobile pos : {Input.GetTouch(0).position}");
    // else normal mouse
		Debug.Log("Ray set for pc");
		ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		Debug.Log($"PC pos : {Input.mousePosition}");
    RaycastHit hit;

    var layer = LayerMask.GetMask("Camion");

    if (Physics.Raycast(ray, out hit, 999f, layer)) // 6 = Layer 6: Camion, on sait qu'on touche un élément du camion
        var foundMat = hit.collider.gameObject.GetComponent<MeshRenderer>().material;
        var foundTruckPart = hit.collider.gameObject.GetComponent<HighlightTarget>().truckPart;
        Debug.Log($"Target {foundTruckPart.name} should be highlighted");

And here’s a screenshot of what I’m trying to hit.

Here’s the rays I’ve got through my debug :

  • PC Ray : Origin: (14.52, 3.66, 79.51), Dir: (-0.99, 0.15, 0.03)
  • Android Ray : Origin: (14.52, 3.65, 79.51), Dir: (-0.99, 0.13, 0.03)

Almost the same, accounting for the small change in direction that seems to be normal. So it should hit in theory, since the ray is the same.

I think I may be missing something about building to Android.

Thanks in advance for any idea you’ve got !

Have you actually passed 6 as your Layer Mask?

Because it should be expressed as a bitmask, not a single layer. If you’re still having issues when that’s fixed, continue following the resource in that link to see if any of the other steps help resolve your issue (eventually landing on visual debugging, where you draw your ray in the scene).

So the problem was coming from the mesh that wasn’t flagged as read write in the import options. It solves the problem!