- Home /
Background Music control issues
I am having trouble controlling the volume of my background sound between scenes. I have a game with multiple scenes and I am attaching the background music to the menu scene. First, I created a GameObject that has a UI canvas and button as children. I also attached an AudioSource with the sound clip, unchecked PlayOnWake. I then created this BgSnd class and attached it to the GameObject on the Menu scene.
When I start the game, the background music starts playing. When I click the button on the menu, I can control the volume on the same menu page. However, if I navigate to other scenes, change the volume and go back to the menu scene, the button doesn't affect the volume again on the initial menu page. In summary, (1) If I am on the menu scene, the button works to toggle the volume on and off (2) If I am on another scene and I toggle the volume off, when I go back to the menu scene, the button doesn't work to toggle the music back on. To do this, I have to navigate to another scene to change the volume.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class BgSnd : MonoBehaviour {
 static bool bgSndPlaying = false;
 bool soundOnOff = false;
 AudioSource bgAudioSrc;
 void Awake () {
     bgAudioSrc = GetComponent<AudioSource> ();
     if(bgSndPlaying == false){
         bgAudioSrc.Play ();
         DontDestroyOnLoad (this);
         bgSndPlaying = true;
     }
     soundOnOff = true;
 }
 public void SoundOnOff(){
     if (soundOnOff == true) {
         bgAudioSrc.volume = 0;
         soundOnOff = false;
     }  else if(soundOnOff == false){
         bgAudioSrc.volume = 1.0f;
         soundOnOff = true;
     }
 }
}
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                