I am making a game where i want in some scenes to play music across them seemlessly and to make the music pause when i get out of these scenes and to resume automatically when iget back to them.
i've tried making a list (array) of the scenes i want to play the music in and check the name of the current scene to see if it is on the list or not.but it doesnt work when i type .contains to check the answer.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DontDestroy : MonoBehaviour {
void Awake(){
print ("WoW");
GameObject[] objs = GameObject.FindGameObjectsWithTag
("music");
if (objs.Length > 1)
{
Destroy (this.gameObject);
}
DontDestroyOnLoad (this.gameObject);
}
}
i use this to keep music playing when switching scenes and not to make it duplicate when i return to the original scene. how ever i want it to work in a certain number of scenes.
First I would use a Singleton pattern instead of allways using Find
Than register a listener to SceneManager.sceneLoaded
Finally I would simply have a list of scenes to check if the loaded scene should play Musik or not
public class PlayMusik : MonoBehaviour
{
private static PlayMusik Singleton;
// Here you reference the secenes where music should be playing
public List<Scene> scenesWithMusik;
// Flag to control of music is playing
private bool isPlayingMusik;
private void Awake ()
{
if(Singleton)
{
Debug.Log("Already another PlayMusik in Scene.", Singleton);
Debug.Log("Destroying this one", this);
Destroy(gameObject);
return;
}
Singleton = this;
DontDestroyOnLoad(gameObject);
// Make sure listener is only added once
SceneManager.sceneLoaded -= OnSceneLoaded;
SceneManager.sceneLoaded += OnSceneLoaded;
}
private void OnDestroy ()
{
// Cleanup listener
SceneManager.sceneLoaded -= OnSceneLoaded;
}
// Called when a scene is loaded
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
Debug.Log("OnSceneLoaded: " + scene.name);
Debug.Log(mode);
// here you handle what should happen with the music e.g.
// if the loaded scene is in scenesWithMusic enable music
// (What should happen if you load a scene additive is up to you)
if(scenesWithMusik.Contains(scene))
{
if(!isPlayingMusik)
{
//Todo: Enable Music here!
isPlayingMusik = true;
}
}
else
{
if(isPlayingMusik)
{
//Todo: Stop Music here!
isPlayingMusik = false;
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.