- Home /
Sending message to one object
Hi, in my game, I want to start a function in a certain object multiple times, from multiple different events, is there anyway to SendMessage to something like a global function that can be triggered easily by multiple events? I use c# btw
Thanks in advance
Answer by zombience · Nov 12, 2013 at 07:58 PM
Check out delegates in C#. They're a super useful way to register functions to other classes so that you can decouple scripts from each other.
On Unity community wiki there is a really great messenger broadcast system that uses the delegate type to create a system to listen for broadcast messages that is much faster than unity's built-in SendMessage method.
It might take a minute to wrap your head around if you haven't used delegates or function pointers before, but you should consider taking the time to work it out. It really helps solve quite a lot of problems.
Now, like any awesome tool, learn it's shortcomings and don't abuse it
:D
Update
I just found this handy tutorial via Unity (which I haven't watched yet, but looks like exactly what you need)
If you plan on having one class calling subscribers which seems to be the case here, you may want to use event ins$$anonymous$$d of delegate (though event are delegates). A public delegate can be assigne dby any class so for instance, ClassA assign $$anonymous$$ethodA to public delegateB in ClassB. Now ClassC assigns $$anonymous$$ethodC to public delegateB in ClassB. Boum, ClassA is no more involved. That is if you are not careful and you did:
delegateB = $$anonymous$$ethodC;
ins$$anonymous$$d of
delegateB += $$anonymous$$ethodC;
Event are safer as they only allowed a class to add or remove one of its members without altering the other subscribers to the event.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to detect multiple trackables in Vuforia 0 Answers