Unity Raycast shoots right through some objects

I made a melee combat system for my game. The code looks like this:

var hit:RaycastHit;
if(Physics.Raycast(transform.position,transform.forward,hit)) {
if(hit.distance<=2.0) {
Debug.LogError("Hit!");
Debug.LogError(hit.collider.tag);
if(hit.collider.tag=="Enemy") {
Instantiate(bloodFX,hit.transform.position,transform.rotation);
}
}
}


However, when an object with the tag "Enemy" stands in front of a "Tree" object, the log tells me that it's hitting the tree tag and not the enemy. What am I doing wrong here? The collision boxes are all correct.

Thanks!

P.S. This is for the ludum dare that ends in 4 1/2 hours so I have to fix this quickly.

• Any chance the enemy object is set to the "Ignore Raycast" layer? Unfortunately this isn't really something we can diagnose just by looking at a few lines of code; for starters, I'd need to see what exactly "the collision boxes are all correct" means. – jhocking Dec 7 '14 at 22:51

Hope this may help : (from Physics.Raycast docu)

Notes: Raycasts will not detect colliders for which the raycast origin is inside the collider. If you move colliders from scripting or by animation, there needs to be at least one FixedUpdate executed so that the physics library can update it's data structures, before a Raycast will hit the collider at it's new position.

• Your note saved my life, thanks – Ashen One Jul 26 at 0:26

I suggest for a quick fix just implement your weapon using collision boxes with trigger assignments then go from there

void OnCollisionEnter(Collision col){
if(col.collider.gameObject.name == "Enemy" /*or tag*/){
//apply damage!
}
}


P.S Thanks for helping me fix send message haha I hope this helps you!

Instead of Physics.Raycast, use Physics.RaycastAll.

I'm pretty sure I've run into this same problem and I don't see it in the documentation for Raycast but it's in RaycastAll that order is not guaranteed. I assume this carries over to Raycast as well. Even if it doesn't and this doesn't solve the issue for you it should be able to assist because it will give you a full list of everything that IS triggering a hit.

RaycastAll returns a RaycastHit[] you can simply iterate over, checking their distances.