Tuesday, March 4, 2025
spot_img

collision detection – In Unity, how can an everyday RigidBody know if it collided with a CharacterController?


You might add a script like this to your object with a Character Controller:

void OnControllerColliderHit(ControllerColliderHit hit) {
    // Examine whether or not the collidee has a physique:
    var hitBody = hit.collider.attachedRigidbody;
    if (hitBody != null) {

        // If that's the case, invoke any matching strategies
        // on that object:
        hitBody.SendMessage(
            "OnHitByController",
            gameObject,
            SendMessageOptions.DontRequireReceiver
        );
    }
}

This successfully provides a brand new message technique, so any script on the Rigidbody that our character hit can implement:

public void OnHitByController(GameObject controllerObject) {
   // Do stuff.
}

…and now it is going to get notified of collisions with character controllers that use the script above.


However that code is “stringly-typed”, which isn’t as environment friendly or as sturdy towards bugs as we will obtain with just a bit extra work:

public interface IControllerCollidable {
    void OnHitByController(GameObject controllerObject);
}

Implement this interface on no matter script you need responding to character controller hits.

Then revise the controller script to…

void OnControllerColliderHit(ControllerColliderHit hit) {
    // Switching to a guard clause for much less nesting.
    var hitBody = hit.collider.attachedRigidbody;
    if (hitBody == null)
        return;

    // Examine if physique has a script connected that desires
    // to learn about controller collisions.
    // (If not, abort)
    if (!hitBody.TryGetComponent(out IControllerCollidable hitScript)
        return;
    
    // Name the tactic we wish.
    hitScript.OnHitByController(gameObject);
}

Word that on this model has no magic strings, and is ready to use a traditional digital operate name as a substitute of looking for matching receivers by title, or doing additional kind casting on the argument.

It is barely extra restrictive in that it’s going to speak to just one script on the Rigidbody we hit, as a substitute of broadcasting to all scripts on that object. We might regulate this to have the identical one-to-many communication as SendMessage, although it comes with some additional price, and we normally have only one script that should deal with this anyway, so I’ve proven the easier/extra environment friendly single-receiver model right here.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisement -spot_img

Latest Articles