- Home /
To broadcast or not to broadcast...
I am debating whether or not it is a good idea to use BroadcastMessage instead of a strongly typed function call. The benefits of BroadcastMessage are clear to me, but I'm not convinced it is a good idea.
I am more for:
if(someObj is SomeType)
{
((SomeType)someObj).DoFunction();
}
Yes, this looks more cumbersome, but it brings developers back to good encapsulation principles and eliminates any possible guesswork.
Answer by Mike 3 · Mar 16, 2011 at 10:49 AM
I much prefer the strongly typed call. You know which object it'll call the function on (SendMessage will send it to all on the gameobject, broadcast will send it to all in the hierarchy downwards), and it saves a bunch of reflection calls
On the downside, it does mean that you need to get a reference to the script(s), which may or may not be easy (Though interfaces tend to help me here, using the non generic version of GetComponent)
I do however prefer the as cast to is+cast though:
SomeType something = someObj as SomeType;
if (something != null)
{
something.DoFunction();
}
Slightly faster, as it doesn't need to check the type twice