/// <summary> Generic method for fading an AudioSource along a Linear-curve (Lerp). </summary> public void FadeAudioSourceLinear(AudioSource audioSource, float from, float to, float fadeTime, System.Action completedCallback = null) { if (!gameObject.activeSelf) { Debug.LogError($"This gameObject '{gameObject.name}' has been deactivated before calling the FadeCoroutine, which will not work on a disabled object. \n" + $"Try moving this '{nameof(AudioSourceUtility)}'-component to a different object, and set its audiosource to the object you tried to disable.", gameObject); return; } if (cancellationToken == null) { cancellationToken = new CoroutineCancellationToken(); } else if (!cancellationToken.IsFinished) { cancellationToken.Cancel(); cancellationToken = new CoroutineCancellationToken(); } StartCoroutine(GenericFadeToVolumeCoroutine(audioSource, Mathf.Lerp, from, to, fadeTime, cancellationToken, completedCallback)); }
/// <summary> Generic Coroutine which does all of the actual fading of the AudioSource along an interpolationMethod-curve (SmoothStep, Lerp, etc). </summary> private static IEnumerator GenericFadeToVolumeCoroutine(AudioSource audioSource, System.Func <float, float, float, float> interpolationMethod, float from, float to, float fadeTime, CoroutineCancellationToken token = null, System.Action completedCallback = null) { token?.CoroutineStart(); var elapsedTime = 0f; while (elapsedTime < fadeTime && (token == null || !token.IsCanceled)) { audioSource.volume = 1f * interpolationMethod(from, to, elapsedTime / fadeTime); elapsedTime += Time.deltaTime; yield return(null); } if (token == null || !token.IsCanceled) { audioSource.volume = 1f * to; } token?.CoroutineFinish(); completedCallback?.Invoke(); }