Unity Raycast shoots right through some objects

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);
                hit.transform.SendMessage("ApplyDamage",25,SendMessageOptions.DontRequireReceiver);
            }
        }
    }

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.

Solutions/Answers:

Answer 1:

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.

Answer 2:

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!

Answer 3:

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.

Documentation: http://docs.unity3d.com/ScriptReference/Physics.RaycastAll.html

References