2013-07-06 55 views
1

我在01級上有GameObjectAudio Sourcescript如下。 當遊戲開始時,腳本運行並開始播放音樂。每次加載場景後,背景音樂變得更響了

我遇到的問題是,每當我加載一個新的水平聲音變得更響。我不明白爲什麼會發生這種情況。有人可以解釋爲什麼,並給出解決方案或指向正確的方向嗎?

using UnityEngine; 
using System.Collections; 

public class MusicManagerScript : MonoBehaviour 
{ 
    public AudioClip[] songs; 
    int currentSong = 0; 

    // Use this for initialization 
    void Start() { 
     DontDestroyOnLoad(gameObject); 
    } 

    // Update is called once per frame 
    void Update() { 
     if (audio.isPlaying == false) { 
      currentSong = currentSong % songs.Length; 
      audio.clip = songs[currentSong]; 
      audio.Play(); 
      currentSong++; 
     } 
    } 
} 
+1

您是否在加載場景時用附加的腳本實例化另一個對象?既然你不摧毀它,你可能最終會有多個音頻源播放同一個剪輯。 –

+0

如果我允許它被破壞,音樂會在另一個關卡加載時停止。 – Ripster

+0

我剛剛嘗試過,它對我來說並不響亮。另一種猜測:嘗試將腳本(和AudioSource)放在主攝像頭上(或任何具有AudioListener組件的東西) –

回答

1

編輯:我看到你的答案是,你的相機只是接近3D音頻源,但是我在這裏把我的答案呢,因爲它是一個共同的問題的常見解決方案。

您每次進入音樂管理器的場景時都會實例化音樂管理器,但是您永遠不會銷燬音樂管理器,而音樂管理器會複製聲音。你需要的是一個單例 - 一種告訴你的代碼永遠不允許多個實例的方法。試試這個:

public class MusicManagerScript : MonoBehaviour 
{ 
    private static MusicManagerScript instance = null; 

    public AudioClip[] songs; 
    int currentSong = 0; 

    void Awake() 
    { 
     if (instance != null) 
     { 
      Destroy(this); 
      return; 
     } 
     instance = this; 
    } 

    // Use this for initialization 
    void Start() 
    { 
     DontDestroyOnLoad(gameObject); 
    } 

    // Update is called once per frame 
    void Update() 
    { 
     if (audio.isPlaying == false) 
     { 
      currentSong = currentSong % songs.Length; 
      audio.clip = songs[currentSong]; 
      audio.Play(); 
      currentSong++; 
     } 
    } 

    void OnDestroy() 
    { 
     //If you destroy the singleton elsewhere, reset the instance to null, 
     //but don't reset it every time you destroy any instance of MusicManagerScript 
     //because then the singleton pattern won't work (because the Singleton code in 
     //Awake destroys it too) 
     if (instance == this) 
     { 
      instance = null; 
     } 
    } 
} 

由於實例是靜態的,每個音樂管理器腳本都可以訪問它。如果它已經被設置好了,它們會在創建時自我毀滅。