- Home /
SendMessage or store reference and call directly?
If an object may or may not have a certain component, is it best to attempt to store a reference to it, or simply use SendMessage without requiring a receiver?
Answer by Jessy · Mar 07, 2011 at 09:54 PM
"Best" sounds like a subject for the forum, but here's my take:
The best thing to do is to not do things to other objects directly. The best thing to do is to have those other objects listen for events, and check for null before firing those events. (The check for null isn't necessary if you are certain that something is going to be listening for the event, but that doesn't sound like a description of your situation.)
I'll have to check that video out after work. When I say "best" I mostly mean a good tradeoff between performance and ease-of-use and code readability. An example of how I would use it is a projectile sends a "Take$$anonymous$$ineticDamage" to whatever it hits. That just seems to make sense to me, but I don't want to do it if it's slow with 50+ projectiles.
Having watched that video it would seem that is an excellent alternative to Broadcast$$anonymous$$essage, but what about events targeted at a specific thing? Should I do gameObject.GetComponent("HitDetector").Take$$anonymous$$ineticDamage() or gameObject.Send$$anonymous$$essage("Take$$anonymous$$ineticDamage");
I need to know more about your scene. It sounds to me, like what I would do, is have the thing being hit get information about the projectile that hit it, and be damaged appropriately. Events aren't a good match when you have to perform checks in each object to see if they are the thing that should get affected, so I don't recommend them, now. I thought you were talking about a single object.