Skip to content

Instantly share code, notes, and snippets.

@made-indrayana
Created October 12, 2021 15:16
Show Gist options
  • Save made-indrayana/eff5678dc5f687dbb714535818ef302c to your computer and use it in GitHub Desktop.
Save made-indrayana/eff5678dc5f687dbb714535818ef302c to your computer and use it in GitHub Desktop.
Simple static Class for AudioSource fade In and Out
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