android - 如何淡出场景之间的音频/音乐?

标签 android audio unity3d fade

启动Android游戏时,我试图让一些音乐淡出。音乐在主菜单中播放,然后在播放器单击播放时淡出。我可以停止播放音乐,只是不会消失。

我试图用这个淡出:

using UnityEngine;
using System.Collections;

public class MusicScript : MonoBehaviour 
{
    static MusicScript instance;
    bool doneFading;

    void Start()
    {
        if(instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }

        else if (instance != this)
        {
            Destroy(gameObject);
        }
    }

    void Update()
    {
        if (Application.loadedLevelName == "Flappy Drone Gameplay Screen")
        {
            FadeMusic();
            if (doneFading == true)
            {
                Destroy(gameObject);
            }
        }
    }

    IEnumerator FadeMusic()
    {
        for (int i = 9; i > 0; i--)
        {
            Debug.Log("here");
            instance.audio.volume = i * 0.1f;
            yield return new WaitForSeconds(0.5f);
            Debug.Log("lowered volume");
        }
        doneFading = true;
    }

}

任何帮助表示赞赏!

最佳答案

在玩了一下Time.deltatime之后,我发现了一种进行淡入淡出的简单方法:)

为遇到相同问题的任何人编写代码(此代码淡出特定场景上的音乐,但保持音乐在所有其他场景上的播放):

using UnityEngine;
using System.Collections;

public class MusicScript : MonoBehaviour 
{
    static MusicScript instance;
    bool doneFading;

    float timer = 5f;

    void Start()
    {
        if(instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }

        else if (instance != this)
        {
            Destroy(gameObject);
        }
    }

    void Update()
    {
        if (Application.loadedLevelName == "Flappy Drone Gameplay Screen")
        {
            FadeMusic();
            if (doneFading == true)
            {
                Destroy(gameObject);
                Debug.Log ("Music destroyed.");
            }
        }
    }

    void FadeMusic()
    {
        if (timer > 0)
        {
            instance.audio.volume -= 0.015f;
            timer -= Time.deltaTime;
        }
        if (instance.audio.volume == 0)
        {
            doneFading = true;
        }

    }

}

关于android - 如何淡出场景之间的音频/音乐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31069743/

相关文章:

java - 使用预编译的正则表达式模式提高速度

haskell - 如何使用Hcodecs编写WAV文件

c# - 如何修复面向玩家的翻转世界空间 UI?

algorithm - 在基于组件的架构 (Unity) 中检测多重冲突的最佳方法

android - 从几个 SharedPreferences 文件中获取 String 并创建 listView

android - 使用音量按钮通过 camera2 api 进行相机缩放

java - Android Firestore查询: get the number of documents within a collection

c# - 如何在 Windows Phone 8 中使用 mp3 文件?

java - 如何暂停播放并停止来自parse.com(android)的音频文件流?

c# - 水物理学。从哪儿开始?