After following Brackeys intro to audio tutorial, I was able to add some sound into my game. I then added two more audio groups, one for sfx and one for music. Also updated the audioManager accordingly. Now each time Play() is called, the audio just plays a little “pop” sound. And the music doesn’t seem to play at all.
This is how the audio sources are called:
FindObjectOfType<AudioManager>().Play("enemyExplosion");
However, I have some bullet prefabs that I simply added audio sources to which work perfectly fine and respond to the audio mixers.
AudioManager.cs
using UnityEngine;
using UnityEngine.Audio;
using System;
public class AudioManager : MonoBehaviour
{
public static AudioManager Instance;
public AudioMixerGroup soundsMixer;
public AudioMixerGroup musicMixer;
public Sound[] sounds;
public Sound[] songs;
void Awake()
{
if(Instance == null){
DontDestroyOnLoad(gameObject);
Instance = this;
} else if (Instance != this)
Destroy(gameObject);
setupSounds(sounds, soundsMixer);
setupSounds(songs, musicMixer);
}
void Start() {
Play("Theme", isMusic: true);
}
public void Play(string name, bool isMusic=false){
Sound s = null;
if(isMusic)
s = Array.Find<Sound>(songs, sound => sound.name == name);
else
s = Array.Find<Sound>(sounds, sound => sound.name == name);
if(s == null){
Debug.LogWarning("Sound: " + name + " not found!");
return;
}
s.source.Play();
}
private void setupSounds(Sound[] soundArray, AudioMixerGroup mixer){
foreach (Sound s in soundArray){
s.source = gameObject.AddComponent<AudioSource>();
s.source.clip = s.clip;
s.source.outputAudioMixerGroup = mixer;
s.source.volume = s.volume;
s.source.pitch = s.pitch;
s.source.loop = s.loop;
}
}
}
Sound.cs
using UnityEngine;
using UnityEngine.Audio;
[System.Serializable]
public class Sound
{
public string name;
public AudioClip clip;
[Range(0f, 1f)]
public float volume;
[Range(-3f, 3f)]
public float pitch;
public bool loop;
[HideInInspector]
public AudioSource source;
}
Here’s what it looks like on Unity side: