Common thing that happens in a million different games: A projectile hits something, and then does something to whatever it hits (damage, plays a sound, flashes color, etc). The reaction to the collision is different depending on the components attached to the objects involved, e.g. a piece of terrain wouldn’t take damage. From what I know, there are two ways to deal with this: SendMessage(), a bunch of GetComponent() calls, or checking tags followed by either method calls depending on the tag. All of these work, but also seem to have their own problems.
SendMessage() seems like by far the most elegant and simple. the sender doesn’t have to care what scripts the other object has, but if any of them have the method, it gets called. However this would result in a lot of SendMessage() calls that don’t do anything, plus I’ve heard that SendMessage() is very slow, so a high-action moment with dozens of collisions happening in a single frame could take a big performance hit.
A bunch of GetComponent() calls to achieve the same thing seems a lot less elegant, but might perform better. What I mean is something like
void OnCollisionEnter(Collision other)
{
IDamageable damageable = other.gameObject.GetComponent<IDamageable>();
if (damageable != null) {//do damage stuff}
IHitFlashable hitFlash = other.gameObject.GetComponent<IHitFlashable>();
if (hitFlash != null) {//do hitflash stuff}
//and so on for any other relevant scripts
}
This is a lot less elegant looking, but I understand that GetComponent<>() might be significantly faster than SendMessage(). However this still has the problem of making a bunch of unnecessary calls.
finally, there is the option of limiting either the SendMessage() or GetComponent<>() calls by checking the tag of the other object and making calls depending on what the tag is. However, then you run into the problem of needing a different tag for each different combination of relevant scripts which could be attached to the other object, and end up with a real messy pile of tags to keep track of.
SO my question is, which way do y’all prefer? or is there a pattern for this situation that I haven’t thought of or read about that trumps them all? I realize that the difference between each method might be so small that its better to leave to personal preference, but I’m the kind of person who likes to do everything the ‘best’ way :]