How can I play an audio in Unity in such a way that when a scene change happens the audio keeps playing without being interrupted?
How can I play an audio in Unity in such a way that when a scene change happens the audio keeps playing without being interrupted?
With the singleton design pattern you can make the GameObjects stay between scenes.
using UnityEngine;
using System.Collections;
using System.Collections.Generic; //Allows us to use Lists.
public class GameManager : MonoBehaviour
{
public static GameManager instance = null; //Static instance of GameManager which allows it to be accessed by any other script.
private BoardManager boardScript; //Store a reference to our BoardManager which will set up the level.
private int level = 3; //Current level number, expressed in game as "Day 1".
//Awake is always called before any Start functions
void Awake()
{
//Check if instance already exists
if (instance == null)
//if not, set instance to this
instance = this;
//If instance already exists and it's not this:
else if (instance != this)
//Then destroy this. This enforces our singleton pattern, meaning there can only ever be one instance of a GameManager.
Destroy(gameObject);
//Sets this to not be destroyed when reloading scene
DontDestroyOnLoad(gameObject);
//Get a component reference to the attached BoardManager script
boardScript = GetComponent<BoardManager>();
//Call the InitGame function to initialize the first level
InitGame();
}
//Initializes the game for each level.
void InitGame()
{
//Call the SetupScene function of the BoardManager script, pass it current level number.
boardScript.SetupScene(level);
}
}
This example of Writing the Game Manager is can notice that in Awake method asks if there is an instance in scene, if true means that this is the instance and if it is false erase this instance and at the end will keep the GameObject that contains this class in scenes.
Since when loading a scene all the GameObjects in the previous scene are destroyed, the DontDestroyOnLoad (gameObject) method prevents it from being destroyed.
You can add this in the script where you manage the audio.