using System.Collections; using System.Collections.Generic; using UnityEngine; public class AudioFader : MonoBehaviour { public AudioSource audioSource; public float fadeDuration = 1.0f; float targetVolume; private void Awake() { targetVolume = audioSource.volume; } // Call this method to fade in the audio public void FadeIn() { print("Fades in audio"); StartCoroutine(FadeAudio(true)); } // Call this method to fade out the audio public void FadeOut() { print("Fades out audio"); StartCoroutine(FadeAudio(false)); } // Call this method to fade out the audio public void FadeOutWithNewTargetVolume(float newTargetVolume) { print("Fades out audio"); StartCoroutine(FadeAudioWithNewTargetVolume(false, newTargetVolume)); } IEnumerator FadeAudio(bool fadeIn) { float startVolume = fadeIn ? 0.0f : targetVolume; float endVolume = fadeIn ? targetVolume : 0.0f; float currentTime = 0.0f; while (currentTime < fadeDuration) { currentTime += Time.deltaTime; audioSource.volume = Mathf.Lerp(startVolume, endVolume, currentTime / fadeDuration); yield return null; } // Ensure the final volume is set to the desired value to avoid rounding errors audioSource.volume = endVolume; if (fadeIn == false) { audioSource.Stop(); } // If you want to stop the audio when fading out, you can uncomment the line below // if (!fadeIn) audioSource.Stop(); } IEnumerator FadeAudioWithNewTargetVolume(bool fadeIn, float newTargetVolume) { float startVolume = fadeIn ? 0.0f : newTargetVolume; float endVolume = fadeIn ? newTargetVolume : 0.0f; float currentTime = 0.0f; while (currentTime < fadeDuration) { currentTime += Time.deltaTime; audioSource.volume = Mathf.Lerp(startVolume, endVolume, currentTime / fadeDuration); yield return null; } // Ensure the final volume is set to the desired value to avoid rounding errors audioSource.volume = endVolume; if (fadeIn == false) { audioSource.Stop(); } // If you want to stop the audio when fading out, you can uncomment the line below // if (!fadeIn) audioSource.Stop(); } }