Get the script instance associated with a collider

So I'm still not completely solid on how a GameObject is composed and how to access its various parts.

I have a reference to a Collider, and need to cast it to the type of a script on the same GameObject, but I'm not sure what this would look like.

My scenario looks like this (using C#):

  • Two objects:
    • `PlayerPrefab`, which has a collider/rigid body, and the `Player` script.
    • `EnemyPrefab`, which has a collider/rigid body, and the `Enemy` script.


public class Player : MonoBehavior {
    public void Kill() { //... }


public class Enemy : MonoBehavior {
    void OnTriggerEnter( Collider other ) {
        Player p = (Player)other;  // This does not work!

So how exactly do I perform that cast in the Enemy script?


Unity uses a composition model - you can access the other components from a gameobject or component using GetComponent. In your case you want something like this:

Player p = other.GetComponent<Player>();