Delegates

@ben what exactly is the point of delegates im still confused about it.

Hi. I will quote from the resource in the observers lesson (Game Programming Patterns)

'Say we’re adding an achievements system to our game. It will feature dozens of different badges players can earn for completing specific milestones like “Kill 100 Monkey Demons”, “Fall off a Bridge”, or “Complete a Level Wielding Only a Dead Weasel”.

This is tricky to implement cleanly since we have such a wide range of achievements that are unlocked by all sorts of different behaviors. If we aren’t careful, tendrils of our achievement system will twine their way through every dark corner of our codebase. Sure, “Fall off a Bridge” is somehow tied to the physics engine, but do we really want to see a call to unlockFallOffBridge() right in the middle of the linear algebra in our collision resolution algorithm?

This is a rhetorical question. No self-respecting physics programmer would ever let us sully their beautiful mathematics with something as pedestrian as gameplay.

What we’d like, as always, is to have all the code concerned with one facet of the game nicely lumped in one place. The challenge is that achievements are triggered by a bunch of different aspects of gameplay. How can that work without coupling the achievement code to all of them?

_That’s what the observer pattern is for. It lets one piece of code announce that something interesting happened without actually caring who receives the notification.’

In the case of our project the CameraRaycaster would be called on update all the time by the CursorAffordance script. This script would look for a change in the layerHit in CameraRaycaster every single frame. This is unrequired and it increases the number of function calls every frame which can lead to low performance and other issues.
Instead of this we use delegates to make it so that the CameraRaycaster tells the CursorAffordance script whenever the value of layerHit changes. The CursorAffordance doesn’t run every frame anymore, it only runs when it is being told from CameraRaycaster that a change was registered.

Hope this helps :).

2 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms