【问题标题】:Is there a way to make music play seemlessly in certain scenes and pause in others in unity?有没有办法让音乐在某些场景中无缝播放而在其他场景中统一停顿?
【发布时间】:2018-12-29 17:49:51
【问题描述】:

我正在制作一个游戏,我希望在某些场景中无缝地播放音乐,并在我离开这些场景时让音乐暂停,并在我回到它们时自动恢复。

我已经尝试制作我想要播放音乐的场景的列表(数组)并检查当前场景的名称以查看它是否在列表中。但是当我键入时它不起作用。包含检查答案。

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);
     }      
}

我用它来在切换场景时保持音乐播放,而不是在我返回原始场景时让它重复。我如何希望它在一定数量的场景中工作。

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    首先我会使用单例模式,而不是一直使用Find

    比注册一个监听器到SceneManager.sceneLoaded

    最后我只需要一个场景列表来检查加载的场景是否应该播放音乐

    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;
                }  
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-27
      • 2021-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多