Hi I found this video on YouTube, about playing music through multiple scenes without the sound breaking:
Playing Seamless Music Across Scenes in Unity 5 With Non-Destroyable Object
Here is the code from the video:
using UnityEngine;
using System.Collections;
public class DontDestroy : MonoBehaviour {
void Awake ()
{
GameObject[] objs = GameObject.FindGameObjectsWithTag("music");
if (objs.Length > 1)
Destroy(this.gameObject);
DontDestroyOnLoad(this.gameObject);
}
}
You attach it to the GameObject that has an audio, and create a tag for it so you can call it in script.
I was just wondering is it possible to add lines to the same code so that once it enters a certain scene, this GameObject stops appearing in it… the audio doesn’t play for that scene…
Okay, so this is the code I used, and it does what I wanted (Unity 5.4):
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class DontDestroy : MonoBehaviour {
void Awake ()
{
GameObject[] objs = GameObject.FindGameObjectsWithTag("music");
if (objs.Length > 1)
Destroy(this.gameObject);
DontDestroyOnLoad(this.gameObject);
}
void Update()
{
if (SceneManager.GetActiveScene().name == "SceneName")
{
Destroy(this.gameObject);
}
}
}
Instead of a ‘SceneName’, you write your own name of the scene where you want audio to stop. Hope this might help someone out. Peace.
EDIT: If you have multiple scenes to go from these, that keep playing the audio, and you want to stop it in multiple instances, just copy the…
if (SceneManager.GetActiveScene().name == "SceneName")
{
Destroy(this.gameObject);
}
… and add the other scene name.
@YoYoYoYo_111_PiPi I tried using this script, but I get this error:
Assets/Scripts/DontDestroy.cs(21,27): error CS0117: SceneManager' does not contain a definition for
GetActiveScene’
Do you know why it might be?