- Home /
One listener for multiple objects?
I am trying to decouple my code by removing the singleton and trying to implement some sort of event, but the problem is that i am not quite sure how to do it the other way around. I can easily have on object that calls multiple listeners, but what about multiple objects trying to call a single listener?
Answer by sbgmr · Sep 05, 2020 at 04:01 PM
Use an observer pattern: https://refactoring.guru/design-patterns/observer. Then the object you want with a listener can subscribe to those multiple objects.
Here is a code example: https://refactoring.guru/design-patterns/observer/csharp/example
Answer by WeirdBeardDev · Sep 05, 2020 at 04:15 PM
The single listener needs to subscribe to each of those events. Here is a code snippet from my project, I'm using C# events (as opposed to Unity Events) but the principle should be the same. I have a corresponding unsubscribe in OnDisable()
.
void OnEnable()
{
ResearchItem.ResearchCompleted += HandleResearchEvent;
Location.Selected += HandleSelectedLocation;
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Question on Events and Delegates 1 Answer
Deactivating object makes events null. What is the best workaround? 1 Answer