- Home /
Multiple kinds of "triggers" raising the same event?
With delegates I can have multiple listeners listening to the same "trigger" (I'm not necessarily talking about Unity Colliders set to isTrigger, even though that is one type of trigger in this case), and when the event is raised they all "hear" it and react to it accordingly. But can I have it the other way around? Multiple "triggers" raising the same event but only one listener reacting to it?
So in my case I have a Timeline PlayableDirector that I want to be able to trigger to play in multiple ways. So I want an listener that just listens for that event, and does not care where it came from; it could be a keyboard key being press, or you click on something in the scene, or you click on an UI element, or you enter a collider in the scene.
I can ofcourse use public properties that just references the PlayableDirector but then I have to make sure to set those references. I wan't the decoupling feature that delegates/events offer. So I want to be able to just add a trigger in the scene that when triggered raises an event, and if no one is listening to that event then nothing happens, but perhaps later on the listener will we spawned into the scene and now if you activate the trigger again something will be listening to that event and then act accordingly.
Like your TV; you can use the remote to turn it on, or you could press a button on the TV to turn it on, or you counld use your smartphone app to turn it on. The TV does not care where the signal to turn it on came from, it just execute the command - no questions asked :)
Answer by FlaSh-G · Apr 03, 2020 at 01:15 AM
The idea behind events (in general) is that senders and responders don't know the other side. They might share semantics so both sides know what the parameter means if you have one, but the senders don't know which (or even how many) responders there are, and the responders usually don't know who sent the event.
Having mutliple senders is easy - anyone can trigger an event. Picking a subset of the responder group however means implementing some sort of logic somewhere that determines who gets to respond. You can do this by writing a bit of code in your class that has the event.
For example:
// Add to and remove from this list with public methods
private static readonly List<Action> responses = new List<Action>();
public static TriggerSingleRandomResponse()
{
responses[Random.Range(0, responses.Count)]();
}