Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Question sound cut

Discussion in 'Audio & Video' started by stigmamax, Oct 10, 2023.

  1. stigmamax

    stigmamax

    Joined:
    Jun 30, 2014
    Posts:
    231
    When I leave an area, I turn off the music but it suddenly stops. What's the best way to make it progressive? THANKS
     
  2. SeventhString

    SeventhString

    Unity Technologies

    Joined:
    Jan 12, 2023
    Posts:
    290
    You can make an AudioFader component that progressively lowers the volume of your AudioSource (in Update, at a predefined rate) and then stops it. You can also implement this kind of logic with a coroutine.

    Here's a simple example to illustrate this:

    Code (CSharp):
    1. public class AudioFader : MonoBehaviour
    2. {
    3.     public AudioSource audioSource;
    4.     public float fadeRate = 0.1f;
    5.     bool fade = false;
    6.  
    7.     void Start()
    8.     {
    9.         if (audioSource == null)
    10.         {
    11.             audioSource = GetComponent<AudioSource>();
    12.         }
    13.     }
    14.  
    15.     void Update()
    16.     {
    17.         if (fade && audioSource != null)
    18.         {
    19.             audioSource.volume = Mathf.Max(0, audioSource.volume - fadeRate * Time.deltaTime);
    20.             if (audioSource.volume == 0)
    21.             {
    22.                 audioSource.Stop();
    23.                 fade = false;
    24.             }
    25.         }
    26.     }
    27.  
    28.     public void StartFadeOut()
    29.     {
    30.         fade = true;
    31.     }
    32. }
     
    KalUnity3D likes this.
  3. stigmamax

    stigmamax

    Joined:
    Jun 30, 2014
    Posts:
    231
    Thanks !