- Home /
Delegates versus class references
I have an open question/concern about delegates/events.
I have units in my project that need to update/send information to a single manager class (one manager class per player). Originally I was going to have each unit have a reference to that manager class and send updates that way. I'm looking to instead implement a delegate/event structure where every unit has a delegate(s) and event(s) and the manager class subscribes to each unit upon creation (manager class is responsible for creating each unit). If units are updating events such resource gathering, spotting enemies, losing territory (essentially each unit could be sending out an event every minute or so and there would be around 30 units per player) is this an inefficient/costly way to be sending messages around?
I really have no practical experience in using delegates so I'm just looking for a little feedback on the matter. Big thanks in advance.
Answer by whydoidoit · Feb 27, 2014 at 07:17 PM
Yes that's very efficient. Just make sure you unwire the events when the units are destroyed.
To clarify - an event call is roughly half the speed of calling a normal function - so in other words it's very fast. $$anonymous$$assively faster than a Send$$anonymous$$essage/Broadcast$$anonymous$$essage - however with the frequency you are talking about even that would be totally fine.
$$anonymous$$ind you a direct reference from Unit to manager sounds good too. If something in the event pattern helps then use that, but it will be slower than a direct call to a child reference.
By 'unwire' I assume you mean something along the lines of: void Dead(Unit u) { for(int i= 0;i
(gang[i]as Unit).OnPress -= Adding;
(gang[i]as Unit).OnDeath -= Dead;
Object.Destroy((gang[i]as Unit).transform.gameObject);
gang.RemoveAt(i);
return;
}
}
}
Thanks for the feedback.
Yes - if you forget there ends up being memory leaks that are hard to fix when Unity nulls all of your references.
Are you wanting to use events because of multicasting the event to multiple listeners?
It's not so much the pattern that helps, I just want the quickest and least-memory-using method of communicating between classes. I have no problem keeping with class references (say that each Unit had a reference to the $$anonymous$$anager class and communicated through that), I just thought it might be less 'expensive' in terms of memory to use a delegate.
Again, thanks.