每次加载场景时背景音乐都会变大

时间:2013-07-06 05:17:00

标签: c# unity3d

我在level01上有一个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 :(得分: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;
        }
    }
}

因为实例是静态的,所以每个音乐管理器脚本都可以访问它。如果它已经设置好,它们会在创建时自行销毁。

相关问题