get sound fade out unitye code example

Example 1: fade text unity

public Text text;
public void FadeOut()
{
    StartCoroutine(FadeOutCR);
}

private IEnumerator FadeOutCR()
{
    float duration = 0.5f; //0.5 secs
    float currentTime = 0f;
    while(currentTime < duration)
    {
        float alpha = Mathf.Lerp(1f, 0f, currentTime/duration);
        text.color = new Color(text.color.r, text.color.g, text.color.b, alpha);
        currentTime += Time.deltaTime;
        yield return null;
    }
    yield break;
}

Example 2: how to fade out music in unity

//credit to gamedevbeginner.com
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class FadeAudioSource {

    public static IEnumerator StartFade(AudioSource audioSource, float duration, float targetVolume)
    {
        float currentTime = 0;
        float start = audioSource.volume;

        while (currentTime < duration)
        {
            currentTime += Time.deltaTime;
            audioSource.volume = Mathf.Lerp(start, targetVolume, currentTime / duration);
            yield return null;
        }
        yield break;
    }
}