Created
October 12, 2021 15:16
-
-
Save made-indrayana/eff5678dc5f687dbb714535818ef302c to your computer and use it in GitHub Desktop.
Simple static Class for AudioSource fade In and Out
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using UnityEngine; | |
public static class Fade | |
{ | |
public static IEnumerator In (AudioSource audioSource, float fadeTime) | |
{ | |
const float startTime = 0f; | |
var currentTime = 0f; | |
audioSource.Play(); | |
while ((int)audioSource.volume != 1) | |
{ | |
audioSource.volume = Mathf.InverseLerp(startTime, fadeTime, currentTime); | |
currentTime += Time.deltaTime; | |
yield return null; | |
} | |
} | |
public static IEnumerator Out (AudioSource audioSource, float fadeTime) | |
{ | |
const float startTime = 0f; | |
var currentTime = 0f; | |
while (audioSource.volume != 0f) | |
{ | |
audioSource.volume = Mathf.InverseLerp(fadeTime, startTime, currentTime); | |
currentTime += Time.deltaTime; | |
yield return null; | |
} | |
audioSource.Pause(); // or stop, depending what do you want to do | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment