Simplified SFX Implementation

Hey Guys! I just wanted to show y’all how I went about adding sound effects to the game.
I first create a Sound Scriptable Object which contains both the clip and volume:

using UnityEngine;

[CreateAssetMenu(menuName = "SoundFX")]
public class Sound : ScriptableObject
{
    [SerializeField] AudioClip clip;
    [Range(0, 1f)] [SerializeField] float volume = 1f;

    public AudioClip GetSoundClip() {
        return clip;
    }

    public float GetClipVolume() {
        return volume;
    }
} 

I then created a SoundManager.cs script which takes in an array of the Sound Scriptable Objects. It then loops through the array and checks if the clip’s name equals the chosen name, plays the clip if true, and then breaks out of the loop:

using UnityEngine;

[RequireComponent(typeof(AudioSource))]
public class SoundManager : MonoBehaviour
{
    [SerializeField] Sound[] sounds;

    public void PlaySFX(string soundName) {
        //The sound clip to play
        AudioClip clip = null;

        // Main Camera
        Camera gameCamera = Camera.main;

        foreach(var sound in sounds) {
            // Assigns clip if name equals chosen name
            if(sound.GetSoundClip().name == soundName) {

                clip = sound.GetSoundClip();

                AudioSource.PlayClipAtPoint(clip, gameCamera.transform.position, sound.GetClipVolume());
                break;
            }
        }

        //If clip doesn't exist
        if(!clip)
            Debug.Log("No clip found with that name...");
    }
}

You can then call the PlaySFX(string name) from where the SoundManager.cs script is attached like so:

GetComponent<SoundManager>().PlaySFX("Explosion");

Please do let me know if you find this helpful :slightly_smiling_face:
Happy Coding!

Privacy & Terms