2015-01-12 40 views
2
多种场景之间交换时播放的连续音乐

我有以下情形在Unity3d

  1. 含音频源组件
  2. 一个关于我们现场

游戏对象脚本中的游戏物体主菜单现场:

using UnityEngine; 
using System.Collections; 


public class ManageMusic : MonoBehaviour { 

private static ManageMusic _instance; 

public static ManageMusic instance 
{ 
    get 
    { 
     if(_instance == null) 
     { 
      _instance = GameObject.FindObjectOfType<ManageMusic>(); 

      //Tell unity not to destroy this object when loading a new scene! 
      DontDestroyOnLoad(_instance.gameObject); 
     } 

     return _instance; 
    } 
} 

void Awake() 
{ 
    if(_instance == null) 
    { 
     Debug.Log("Null"); 
     //If I am the first instance, make me the Singleton 
     _instance = this; 
     DontDestroyOnLoad(this); 
    } 
    else 
    { 

     //If a Singleton already exists and you find 
     //another reference in scene, destroy it! 
     if(this != _instance){ 
      Play(); 
      Debug.Log("IsnotNull"); 
      Destroy(this.gameObject); 
     } 
    } 

} 
public void Update() 
{ 
    if (this != _instance) { 
     _instance=null; 
    } 
} 
public void Play() 
{ 
    this.gameObject.audio.Play(); 
} 

关于我们Back button script:

using UnityEngine; 

using System.Collections;

public class Back_btn:MonoBehaviour void OnMouseDown(){ Application.LoadLevel(“MainMenu”);

} 

}

enter image description here enter image description here 当我点击关于我们按钮的Game Music object再玩了,我可以听到音乐,但是当我返回到主菜单中没有音乐仍在播放。我可以看到,当我返回到主菜单和音频监听器的音量对象没有被破坏的音量设置为1,但我想不出任何人都可以帮我的问题

回答

1

你需要一个单身这个。 Unity Patternsa great post about singleton usage in Unity3D environment。尝试执行该网站中指定的这种持久单体模式模式。

持久性辛格尔顿

有时候,你需要你的单身人士场景之间持续(对 例如,在这种情况下,你可能想要一个场景 过渡期间播放音乐)。一种方法是在你的 singleton上调用DontDestroyOnLoad()。

public class MusicManager : MonoBehaviour 
{ 
    private static MusicManager _instance; 

    public static MusicManager instance 
    { 
     get 
     { 
      if(_instance == null) 
      { 
       _instance = GameObject.FindObjectOfType<MusicManager>(); 

       //Tell unity not to destroy this object when loading a new scene! 
       DontDestroyOnLoad(_instance.gameObject); 
      } 

      return _instance; 
     } 
    } 

    void Awake() 
    { 
     if(_instance == null) 
     { 
      //If I am the first instance, make me the Singleton 
      _instance = this; 
      DontDestroyOnLoad(this); 
     } 
     else 
     { 
      //If a Singleton already exists and you find 
      //another reference in scene, destroy it! 
      if(this != _instance) 
       Destroy(this.gameObject); 
     } 
    } 

    public void Play() 
    { 
     //Play some audio! 
    } 
} 
+0

没有代码工作完全相同的地雷?如果我想测试你的代码,我应该怎么做?只需将你的代码替换掉我的另一个问题,我没有尝试你的代码,但在我的特殊情况下,如果单身人士是在'主菜单'中创建的,它的脚本将保留在'about'场景中,但是当我返回到主菜单是单身持续并继续玩,否则它会消失或将再次玩? – Sora

+0

我不确定你的'if else'代码块是如何工作的,但我敢打赌,它不会像你打算的那样工作。请继续阅读链接中的模式。玩这个代码片段,并尝试改变它,以便它符合您的需求。该脚本将附加到的游戏对象只会在游戏加载时创建,并且在更改场景时不会被删除,因此音乐会一直播放,直到您停止为止(如玩家将场景更改为游戏玩法并且您告诉那么脚本只能停止播放)。 – Varaquilex

+0

你能检查一下我的编辑吗 – Sora