SphereCast doesn't work with a layerMask

Or at least, as far as I can tell it doesn’t. To test, I was doing a Raycast and a SphereCast in the same frame with exactly the same parameters (except the obvious addition of the range parameter to SphereCast), both with a layerMask var I set up as a public member variable and set in the editor. The SphereCast would fail even when the Raycast evaluated to true.

Try this code, and make sure you place a large object with a collider (like a cube or something) in front of the object you attach this to.

public var layerMask : LayerMask; //set this to something in the editor
public var sphereRadius : float = 10.0;

function Update(){
	
	var hit : RaycastHit;

	if(Physics.Raycast(transform.position, transform.forward, hit, 1000, layerMask)){
		Print("Raycast succeeded.");
	}
	else{
		Print("Raycast failed.");
	}
	
	if(Physics.SphereCast(transform.position, sphereRadius, transform.forward, hit, 1000, layerMask){
		Print("SphereCast succeeded.");
	}
	else{
		Print("SphereCast failed.");
	}

}

Or am I doing something wrong?

Keep in mind that if the sphere starts inside or partial inside the object you want to hit it won't detect an hit. A radius of 10 seems quite big (i don't know the object relative scales you use). What exactly do you want to detect?

btw. i guess the second Raycast should be a SphereCast ;)

In general keep in mind that MeshColliders can only be hit from one side (outside). Convex MeshCollider or any Primitive colliders are volume-colliders (can't have holes or single planes / trinagles). If a Raycast starts from the inside it does never hit the object.

edit

I’ve just realised you’ve used the LayerMask utility-class, but the wrong way :wink:

The layermask is a bit-flag (32-bit integer value) where each bit represents one of the 32 layers. You have to use `layerMask.value` in your Ray- / Spherecast.