I am starting with Unity and I would like to make a 2d game with different background music for each scene.
So far I have created two scenes with theoretically a different background scene each, and one of the scenes contains a settings menu with which I can change the music volume.
However, when I click the play button the background music plays for 1 second and suddenly stops.
This is the script for the audio manager:
using System;
using UnityEngine;
public class AudioManager : MonoBehaviour
{
public static AudioManager instance;
public Sound[] sounds;
void Awake()
{
if (instance != null)
{
Destroy(gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(gameObject);
}
foreach (Sound s in sounds)
{
s.source = gameObject.AddComponent<AudioSource>();
s.source.clip = s.clip;
s.source.outputAudioMixerGroup = s.mixer;
s.source.volume = s.volume;
s.source.pitch = s.pitch;
s.source.loop = s.loop;
}
}
public void Play(string sound)
{
Sound s = Array.Find(sounds, item => item.name == sound);
s.source.Play();
}
public void Pause(string sound)
{
Sound s = Array.Find(sounds, item => item.name == sound);
s.source.Pause();
}
}
This is the script I use to change the music between scenes:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SwapScenes : MonoBehaviour
{
void Update()
{
if (SceneManager.GetActiveScene().name == "Xf")
{
AudioManager.instance.Pause("MenuM");
AudioManager.instance.Play("XfM");
}
if (SceneManager.GetActiveScene().name == "Menu")
{
AudioManager.instance.Pause("XfM");
AudioManager.instance.Play("MenuM");
}
}
}
This is the script for the volume in settings menu:
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.Audio;
public class MenuEvents : MonoBehaviour
{
public Slider volumeSlider;
public Slider musicVolumeSlider;
public AudioMixer mixer;
public AudioMixer musicMixer;
private float value;
private float musicValue;
private void Start()
{
Time.timeScale = 1;
mixer.GetFloat("volume", out value);
musicMixer.GetFloat("musicVolume", out musicValue);
volumeSlider.value = value;
musicVolumeSlider.value = musicValue;
}
public void SetVolume()
{
mixer.SetFloat("volume", volumeSlider.value);
musicMixer.SetFloat("musicVolume", musicVolumeSlider.value);
}
I have this in the editor:
I would be grateful if somebody could help me with this issue or offer me any alternative.

