Alternative SFX Implementation

Here’s a possible alternative implementation for SFX using a Sound Manager inspired by Trung over in Udemy Q&A.

public class SoundManager : MonoBehaviour {

    [SerializeField] AudioClip playerShotSFX, playerDeadSFX, enemyDeadSFX, enemyShotSFX;
    [SerializeField] [Range(0, 1)] float masterVolume = 1f;
    [SerializeField] [Range(0, 1)] float sFXVolume = 1f;
    [SerializeField] [Range(0, 1)] float playerShotVolume = 1f;
    [SerializeField] [Range(0, 1)] float playerDeadVolume =  1f;
    [SerializeField] [Range(0, 1)] float enemyShotVolume = 1f;
    [SerializeField] [Range(0, 1)] float enemyDeadVolume = 1f;

    public void TriggerPlayerShotSFX()
    {
        AudioSource.PlayClipAtPoint(playerShotSFX, 
            Camera.main.transform.position, 
            playerShotVolume * (sFXVolume * masterVolume));
    }

    public void TriggerPlayerDeadSFX()
    {
        AudioSource.PlayClipAtPoint(playerDeadSFX,
            Camera.main.transform.position,
            playerShotVolume * (sFXVolume * masterVolume));
    }

    public void TriggerEnemyShotSFX()
    {
        AudioSource.PlayClipAtPoint(enemyShotSFX,
            Camera.main.transform.position, 
            enemyShotVolume * (sFXVolume * masterVolume));
    }

    public void TriggerEnemyDeadSFX()
    {
        AudioSource.PlayClipAtPoint(enemyDeadSFX, 
            Camera.main.transform.position, 
            enemyShotVolume * (sFXVolume * masterVolume));
    }
}

Here’s an example of calling the method.

[SerializeField] SoundManager soundManager;
...
private void Die()
    {
        Destroy(gameObject);
        soundManager.TriggerPlayerDeadSFX();
    }

I’m hoping this doesn’t come back to bite me when we add music later :smiley:

4 Likes

Hey, just came up with the same idea, haha :slight_smile:

Well done. Coming from Java, this is a very familiar concept and I will expand upon it in my future personal projects. Thanks for sharing! :ok_hand:

Nice! I ended up doing the same thing. It just feels cleaner to me. I don’t know if there is any extra resource usage for calling another script.

I didn’t know you could stack variables like the first line. That is helpful.

Privacy & Terms