Detect RaycastHit on Character Controller

As you may know, colliders can’t be used with character controllers. I have a script using raycast that is supposed to detect a hit on the player, which has a character controller component attached. How can I get the player to detect a raycast hit?

2 Answers

2

There are a lot of things that can go wrong with ray casts: bad direction, too short, hitting a trigger box by mistake… so best to do lots of checking. Try to check each step. This would check where it ends and what you hit:

var rayEnd : Transform // drag in a small red cube w/no collider
var hitWho : string; // debugging

  // Update:
  // so we can see where ray goes:
  rayEnd.position = transform.position + forward*range;

  if(Physics.Raycast( ... ) {
    hitWho="hit:"+hit.transform.name;
    ...
  }
  else hitWho="<no hit>";

Some people also recommend using Debug.DrawRay to see the path, but the inputs aren’t the same as raycast, so it’s easy to draw it in the wrong place and confuse yourself even more.

I don't understand the purpose of doing that. It doesn't seem to work.

Yeah, I understand it. It's the way that my code and his worked together.

if(hit.collider.gameObject.tag == “Player”){
// Do Stuff
}

It doesn't help anymore than my code: if (hit.collider.name == "Player") { // Code }

Works fine for me .. Post your code.

Char controllers are really odd beasts. Their built-in capsules count as rigidbody colliders for most purposes. Sort of an undocumented(?) feature.

I never thought of doing it that way :) The player's health still doesn't decrease. Why?

Do you get any errors in the console? If so it's most likely that the object you've hit, that is named "Player" doesn't have a Health script attached. If you don't get an error you doing something wrong. I've just took a look at your prefab package. It's a bit messed up on my end. Your scripts are not included and the child objects have no name. Furthermore you still have an additional capsule collider as child which might intercept your raycast. Remove this collider. Again, the CharacterController IS already a collider.