Custom made Sound Manager Script

Roger Vieira

Game Designer
Sound Designer
Game Developer
Unity
Visual Studio Code
using UnityEngine;

using UnityEngine.Audio;

public class SoundManager : MonoBehaviour
{
public static SoundManager instance;

[SerializeField] private AudioSource soundObject;
[SerializeField] private AudioMixer audioMixer;
[SerializeField] private AudioMixerGroup musicAudioGroup;

[Header("Audio Clips")]
public AudioClip musicAudioClip;
public AudioClip mergeAudioClip;
public AudioClip explodeAudioClip;
public AudioClip clickAudioClip;

[Header("Audio Volume On Start")]
[SerializeField][Range(0f, 1f)] private float musicStartVolume;
[SerializeField][Range(0f, 1f)] private float soundStartVolume;

public float soundVolume { get; private set; }
public float musicVolume { get; private set; }

private void Awake()
{
if (instance == null)
{
instance = this;
PlayMusic();
DontDestroyOnLoad(gameObject);
}
}

private void Start()
{
musicVolume = PlayerPrefs.GetFloat("musicVolume", 1f);
soundVolume = PlayerPrefs.GetFloat("soundVolume", 1f);
audioMixer.SetFloat("MusicVolume", Mathf.Log10(musicVolume) * 20f);
audioMixer.SetFloat("SoundFXVolume", Mathf.Log10(soundVolume) * 20f);
}

public void ChangeMusicVolume(float volume)
{
musicVolume = volume;
audioMixer.SetFloat("MusicVolume", Mathf.Log10(musicVolume) * 20f);
PlayerPrefs.SetFloat("musicVolume", musicVolume);
}

public void ChangeSoundVolume(float volume)
{
soundVolume = volume;
audioMixer.SetFloat("SoundFXVolume", Mathf.Log10(soundVolume) * 20f);
PlayerPrefs.SetFloat("soundVolume", soundVolume);
}

public void PlayMusic()
{
AudioSource audioSource = Instantiate(soundObject, transform.position, Quaternion.identity);
DontDestroyOnLoad(audioSource.gameObject);
audioSource.outputAudioMixerGroup = musicAudioGroup;
audioSource.clip = musicAudioClip;
audioSource.loop = true;
audioSource.volume = musicStartVolume;
audioSource.Play();
}

public void PlaySoundFX(AudioClip audioClip, Transform spawnTransform)
{
AudioSource audioSource = Instantiate(soundObject, spawnTransform.position, Quaternion.identity);
DontDestroyOnLoad(audioSource.gameObject);
audioSource.clip = audioClip;
audioSource.volume = soundStartVolume;
audioSource.Play();

float clipLenght = audioSource.clip.length;
Destroy(audioSource.gameObject, clipLenght);
}
}

Partner With Roger
View Services

More Projects by Roger