How to call method from other class

I tried this

public class Obstacle : MonoBehaviour {
    PlayerContorler pc = new PlayerContorler ();
    void OnTriggerEnter2D(Collider2D collider){
        if (collider.gameObject.name == "Player") {
            pc.death();
    }
    }}
 public  void death(){
        //die
        Destroy (this.gameObject);


}

but that doesn’t work

You need to call the method on the colliders PlayerController like so:

public class Obstacle : MonoBehaviour
{
    void OnTriggerEnter2D(Collider2D collider)
    {
        if (collider.gameObject.name == "Player")
        {
            var pc = collider.GetComponent<PlayerContorler>();
            pc.death();
        }
    }
}

Use
collider.SendMessage ("death ")

This may help with the general concepts. The key piece you are missing is GetComponent.

@1Piotrek1 SendMessage is ok to use once in a blue moon, but it’s expensive so don’t use it often!

It’s not horrible but it does get worse if you have a lot of components because it tries to send the message to every component on the GameObject.

It’s practical for controlled scenarios, basically the same as GetComponent<>() when you aren’t caching it. If you could cache a GetComponent and reuse it then that would always be better - assuming you are only targetting one component.

1 Like

The key difference between SendMessage and GetComponent has nothing to do with the performance. It’s all to do with the information you have about the other GameObject.

If you know a specific component exists, then get component is ideal. On the other hand if there might be more or less then one receiver, SendMessage is better.

Note that in most cases SendMessage should be replaced by the faster and less error prone ExecuteEvents. Abandoning compile time checking and calling methods by strings is always a risky idea.

Ok I use now this :

    PlayerContorler pc;
    void Awake(){
        GameObject player = GameObject.Find ("Player");
         pc = player.GetComponent<PlayerContorler> ();
    }
    void OnTriggerEnter2D(Collider2D collider){
        if (collider.gameObject.name == "Player") {
            pc.death();
    }
    }

Thanks for the replies :smile: