|
How can I simultaneously invoke all instances of a function without it being a static function?
(comments are locked)
|
|
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. That is what I have been looking for. Thank you for sharing. Scripts work well but I wonder if I have an abstract class for Broadcaster, how can I reach to event?
Apr 25 at 09:24 AM
emrahsifoglu
(comments are locked)
|
|
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: Given: Then: Would cause: I have made the InstanceList pattern available for download through NuGet InstanceListPattern Thank you. It is very useful.
Apr 25 at 07:44 PM
emrahsifoglu
Here's a version that supports this on MonoBehaviours: Any script which inherits from MonoCollection has an all static member that can be used to access the instances. The to call all methods:
Apr 26 at 06:21 AM
whydoidoit
(comments are locked)
|
