If ExecuteEvents.Execute requires a target, why wouldn't I call the method directly?

I’m trying to broadcast a message to any MonoBehavior listening. I found the following documentation for Unity’s messaging system. Redirecting to latest version of com.unity.ugui

One thing I found odd is that ExecuteEvents.Execute requires the target to be passed in. If the target needs to be known, why wouldn’t I call the method directly? What benefit does dispatching this message give?

It’s similar to how ‘SendMessage’ works but more strongly typed.

The target is the ‘GameObject’ to search for the interface type on as a component. So you don’t actually need a reference to the actual component/s… but to the gameobject.

It’d be the equivalent of doing:

foreach(var c in target.GetComponents<IMessageInterface>())
{
    c.Foo(bar);
}

But more concisely (and I believe it doesn’t have the array overhead of GetComponents).

Also ExecuteHierarchy will traverse the hierarchy for you as well.

What if I don’t know the game object? Is there a way to broadcast globally to anything listening?

Not with ExecuteEvents, no.

But you can write a global broadcaster similar to it.

Here’s my own personal implementation of such a thing (note this is not copy/paste since it has some dependencies that won’t resolve… it’s intended more for demonstration pusposes):

1 Like