- Home /
Coalesce all classes implementing a specified interface into a static list?
I have an interface called IHourlyUpdate and a manager that invokes an HourTick() method every second. I want to use a foreach() loop in HourTick() that invokes HourUpdate() in every class in the list (HourUpdate() is a method in the IHourlyUpdate interface). How do I grab every class implementing an interface and merge them into a single static list?
Answer by zombience · Mar 28, 2019 at 02:42 AM
It depends on how you want to organize your code.
Probably the most straightforward way to do so would be to place a public method on your manager which would allow any object implementing the IHourlyUpdate interface to register itself when it becomes instantiated.
something like:
public class HourlyUpdateManager
{
List<IHourlyUpdate> allUpdateObjects = new List<IHourlyUpdate>();
public void RegisterUpdater(IHourlyUpdate obj)
{
if(allUpdateObjects.Contains(obj)) return;
else allUpdateObjects.Add(obj);
}
void UpdateTick()
{
foreach(var obj in allUpdateObjects)
{
obj.HourUpdate();
}
}
each object implementing your interface would need to be responsible for finding the manager and registering. Or whatever object creates the interface would need to do so. That will depend entirely on how you're organizing things.
So every object using IHourlyUpdate would run RegisterUpdater on Awake? Does that mean I should put RegisterUpdater in the interface?
If each object is a $$anonymous$$onobehaviour then that would be an easy way to do it
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
List of Transforms updating all items when adding variable. 1 Answer
How to modify array values? 1 Answer
List of Interface classes 1 Answer
Is there a way to remove array entries in the editor? 4 Answers