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);
}
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();
}
}
}
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.
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.