- Home /
Question by
ibushko1 · Aug 08, 2021 at 05:44 PM ·
audioscript.scenescripting beginner
How to mute background music in just one scene
Hello! I'm trying to mute my background music in just one of my scenes. I'm thinking of putting something in my background audio script referencing the specific scene I want the background audio to be muted in and put it on pause? or destroying it? I'm pretty new to unity so thanks for the help!
Background Audio script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BackgroundAudio : MonoBehaviour
{
private static BackgroundAudio instance = null;
public static BackgroundAudio Instance
{
get { return instance; }
}
void Awake()
{
if (instance != null && instance != this)
{
Destroy(this.gameObject);
}
else
{
instance = this;
}
DontDestroyOnLoad(this.gameObject);
}
}
Change between scenes script: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement;
public class Enter : MonoBehaviour
{
//this is to switch between the introduction scene and the main scene
// sceneloader and a integer will allow me to enter the number of the scene into the inspector to show what scene I want to switch to
public void SceneLoader(int SceneIndex)
{
SceneManager.LoadScene(SceneIndex);
}
}
Comment
Answer by Gustav2302 · Sep 04, 2021 at 03:52 PM
Adding an AudioSource Component to the gameobject with the BackgroundAudio script and the following function in said script (where index is the scenenumber where the music should be paused), should do the trick:
private void OnDidOpenScene()
{
if (SceneManager.GetActiveScene().buildIndex== index)
{
GetComponent<AudioSource>().Pause();
}
else
{
GetComponent<AudioSource>().Play();
}
}