- Home /
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?
Answer by Squeegy · Apr 26, 2010 at 07:40 PM
I would assume that
- There is no functional difference as long as only one script implements that method.
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.
Answer by dhendrix · Apr 26, 2010 at 07:42 PM
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.
According to the post, GetComponent is probably as slow as Send$$anonymous$$essage; the performance gain comes from caching the component after a single call to GetComponent.
Answer by Molix · Apr 26, 2010 at 08:05 PM
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 ); }
Your answer
![](https://koobas.hobune.stream/wayback/20220612192428im_/https://answers.unity.com/themes/thub/images/avi.jpg)