Unity: Creating an Event Based Sound Effects Manager Using Delegates
Music and sound effects are an amazing way to develop immersion into your application. From informing the user to an event, to immersing the user in a scene, the use of sound can be incredibly important. This is going to be a quick article on how we can create a sound effects manager that is based on events using Action delegates.
Prerequisites
For this demo I am going to be using a simple 2D space shooting game. We will be using Action types, event listeners, serialized fields, arrays, Audio Clips, the Audio Source component, as well as four sound effects. This will also be utilizing 3 built-in methods: Awake, OnEnable, and OnDisable.
The logic behind this method is that we are going to be listening for events and then dynamically setting the AudioClip for the Audio Source component depending on which events get fired.
The very first thing we need to do is identify events that we want to tie sound effects to. For this example, I identified the following events:
- When the player gets damaged.
- When an enemy is destroyed.
- When a laser is fired.
- When an asteroid is destroyed.
Steps
Step 1: Setting Up The Game Object
We are going to create a script called SoundEffects and add that script as a component to a new…