What's the difference between SendMessage and GetComponent?

If for instance you were doing weapon damage you could use SendMessage("ApplyDamage",20) or you could use GetComponent(EnemyScript).ApplyDamage(20). One doesn't require any knowledge of what scripts are on the receiving end but apart from that what's difference? Which is faster? Is there a reason to use one instead of the other?

I would assume that

  1. There is no functional difference as long as only one script implements that method.
  2. `GetComponent` would be faster since it does not have to look for method on all attached components.

I would use `SendMessage` when implementing a protocol of messages that many different scripts can optionally repsond to. This allows you to have a good deal of flexibility. You can simply tell an object to `DoStuff` without having to know what kind of object it is or what scripts are on it. It is left up to the object itself to know how to do it's own stuff.

But if enemies are the only things that you `ApplyDamage` to, it makes more sense to call it directly. Use the `SendMessage` route if you want to have a variety of scripts trigger when you `ApplyDamage` to an object.

SendMessage is quite a bit slower than GetComponent, though using it a few times per frame is not so bad, and it is much more convenient. Generally you only have to worry about it on iPhone development. But either way, its usually best to design first, and optimize later.

This forum topic has more info on the subject, including time comparisons.

Make sure you read that link carefully! It states that GetComponent is "probably at least as slow as" SendMessage. The performance gain comes from caching the reference to the target (i.e. calling GetComponent once in Start()). e.g. (C#)

private EnemyScript enemy = null;

void Start()
{
  enemy = GetComponent(typeof(EnemyScript)) as EnemyScript;
}

void DoStuff()
{
  enemy.ApplyDamage( 20 );
}