0
\$\begingroup\$

I'm creating an audio script for my character and it changes the sounds based on the textures it is walking on.

Said character uses a Character Controller component from Unity and I thought of using it to detect collision using ControllerColliderHit. However, my char has a parent that has it while the character itself that has the animator doesn't.

How can I call ControllerColliderHit using the parent CharacterController? Or if there's another better way of doing this, I would appreciate it.

\$\endgroup\$
1
  • \$\begingroup\$ If you hand over all collision events to a single OnControllerColliderHit, you need to distinguish whether the collision is from the ground, the wall or other objects, which makes things complicated. My suggestion is to add a Animation Event named "foot on the ground" to the running animation, which triggers a downward ray detection and plays a sound according to the material. \$\endgroup\$
    – Mangata
    Jan 7 at 5:31

1 Answer 1

1
\$\begingroup\$

Use a Unity Event to relay the message anywhere you want.

using UnityEngine.Events;

public class ControllerEventRelay : MonoBehaviour {

    public UnityEvent<ControllerColliderHit> onColliderHit;

    void OnControllerColliderHit(ControllerColliderHit hit)
    {
        onColliderHit?.Invoke(hit);
    }
}

Put this script on the parent that has the character controller, then use the event to wire it up to any function accepting a ControllerColliderHit argument on any component on any object you like. You can even wire up multiple listeners to all respond to each individual collision event.

It looks like this in the Inspector:

Inspector Preview

Click the "+" button to add a new listener, and select the object that has the function you want to invoke. Then select the component that has that function from the drop-down, and select the function from the "Dynamic ControllerColliderHit" section at the top. Any public instance method accepting a ControllerColliderHit as its sole argument will show up as an option to choose here.

You can also add listeners in code:

onColliderHit.AddListener(functionToCall);
\$\endgroup\$
4
  • \$\begingroup\$ Hi, thanks for the answer! How can I wire it up with functions that accept ControllerColliderHit? I'm not familiar with using Events in Unity, so I'm a little confused. Just call in the Event in place of the argument? \$\endgroup\$
    – Astolfo
    Jan 7 at 18:43
  • \$\begingroup\$ I've edited the answer to show how to select what functions to call when the controller collides. \$\endgroup\$
    – DMGregory
    Jan 7 at 19:14
  • \$\begingroup\$ Thanks! Going to test it out \$\endgroup\$
    – Astolfo
    Jan 8 at 1:35
  • \$\begingroup\$ Tried it now and it solved the problem perfectly! Thanks for the help. \$\endgroup\$
    – Astolfo
    Jan 8 at 19:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .