Skip to content

Instantly share code, notes, and snippets.

@wesen
Created July 12, 2018 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wesen/9d5790d3f528916c7308bd39dbdabe45 to your computer and use it in GitHub Desktop.
Save wesen/9d5790d3f528916c7308bd39dbdabe45 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class VolumeFader : MonoBehaviour {
private AudioSource _as;
private float _originalVolume;
private IEnumerator _fadeCoroutine;
void Start() {
_as = GetComponent<AudioSource>();
_originalVolume = _as.volume;
}
public void FadeOut(float fadeLength_seconds) {
if (_fadeCoroutine != null) {
StopCoroutine(_fadeCoroutine);
}
_fadeCoroutine = _volumeFadeCR(0.0f, fadeLength_seconds);
StartCoroutine(_fadeCoroutine);
}
public void Play() {
if (!_as.isPlaying) {
_as.volume = _originalVolume;
_as.Play();
} else {
if (_fadeCoroutine != null) {
StopCoroutine(_fadeCoroutine);
_fadeCoroutine = _volumeFadeCR(_originalVolume, 0.1f);
StartCoroutine(_fadeCoroutine);
}
}
}
IEnumerator _volumeFadeCR(float targetVolume, float fadeLength_seconds) {
float startTime = Time.time;
float startVolume = _as.volume;
float volumeRange = (startVolume - targetVolume);
float volumeStep = volumeRange / fadeLength_seconds;
while (Time.time <= (startTime + fadeLength_seconds)) {
_as.volume -= volumeStep;
yield return new WaitForSeconds(0.01f);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment