Search code examples
androidaudiounity-game-enginefade

How to fade out audio/music between scenes?


I'm trying to get some music to fade out when I start my android game. The music plays in the main menu and then should fade out when the player clicks play. I can get the music to stop, just not fade out.

Im trying to fade out using this:

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

}

Any help is appreciated!


Solution

  • After a bit of playing about with Time.deltatime I found a simple way of doing a fade :)

    Code for anyone in the same problem (this code fades out music on a particular scene but keeps the music playing for all other scenes):

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