How can I simultaneously invoke all instances of a function without it being a static function?
asked May 12 '12 at 10:21 PM
You can't invoke "all instance methods". The memory addresses of those functions are not known until runtime, so the CLR wouldn't know what to invoke where. The whole reason that you can link against a static function is that its memory address is known when the compiler generates the code.
With that said, you can use events and delegation to create a broadcasting class that all your objects subscribe to. When the broadcaster invokes its event, all the listener get the message, which sounds exactly like what you want to do. Here's an example:
Attach the following script to the BroadcastObject:
Attach this script to the Listeners:
That should do it. When you press the GUI button, all listeners subscribed to the broadcaster receive the event. In this case, all write "Message received!" to the console. If you want to send actual arguments to each listener, create a custom EventArgs class that carries those parameters. A use case might be an event-driven NPC scheduler for an RPG game. Rather than having each NPC check the time every frame, you instead have them subscribe to the time-of-day broadcaster, which sends an event whenever the the time has meaningfully changed ("Time to go to bed!") via the EventArgs.
The standard event pattern in C# can take a while to grok. Try it out in an empty project first, then adapt it for your project step by step. I can post the example project if needed.
There is one way though. It's a pattern I call the
I've written about the military pattern which is a special use case for the
The basic idea is to have a list of all instances, then through a static function; call a method on all instances. Here is an example:
I have made the InstanceList pattern available for download through NuGet InstanceListPattern