Observer Pattern: Add Speed Boost Pickups With C# Events In Unity

Electric Sunset — Game Dev Unlocked Game Jam #1

Using Boost with Tiny Car Controller

TinyCarController.cs contains a public method named setBoostMultiplier(), meaning a speed boost can be temporarily applied to a vehicle from another MonoBehavior script. “Electric Sunset” was submitted to the game jam with persistent speed boost objects in the form of electric orbs, each of which had an attached PowerBoost.cs script handling the pickup interaction with the surfer van.

Electric Power Boosts ReadyTo Be Picked Up By The Surfer Van
First version of PowerBoost without Events

C# Events, Delegates and the Observer Pattern

The Observer Pattern can be used with C# Events as a lightweight notification system that decouples the object sending a message from the object receiving it. In the below revision of PowerBoost, the System namespace is used to access the Action delegate to define OnBoostEvent. This boost event is invoked every time the surfer van collides with an electric power up.

Revised version of PowerBoost.cs with Events
  1. Handle the surfer van’s subscription to OnBoostEvent
  2. Execute the business logic inside method HandleBoost() when the event is triggered

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store