Created
July 12, 2018 20:14
-
-
Save wesen/9d5790d3f528916c7308bd39dbdabe45 to your computer and use it in GitHub Desktop.
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 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