- Home /
Fade Sound OnTriggerExit
Hey there,
I've got audio to trigger on enter and stop on exit, but I'm unsure how I'd go about fading it out. I don't need it to fade OnTriggerEntry, only on exit. I have no C# knowledge, so any help would be amazing.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SoundTrigger : MonoBehaviour {
public AudioSource source;
public AudioClip clip;
private bool isPlayed;
public void Awake() {
source = GetComponent<AudioSource>();
isPlayed = false;
}
public void OnTriggerEnter(Collider other) {
if (!isPlayed) {
source.Play();
isPlayed = true;
}
}
public void OnTriggerExit(Collider other) {
if (source.isPlaying) {
source.Stop();
}
isPlayed = false;
}
}
Answer by haizathaneefa · Jun 29, 2020 at 04:52 AM
Hello, reduce the volume to 0 and then stop the audio. Basically, you need a coroutine for this. Something like
public void OnTriggerExit(Collider other)
{
if (other.CompareTag("yourplayertag"))
{
StartCoroutine(AudioController.FadeOut(audioSource, 1f));
}
}
public static class AudioController
{
public static IEnumerator FadeOut(AudioSource audioSource, float FadeTime)
{
float startVolume = audioSource.volume;
while (audioSource.volume > 0)
{
audioSource.volume -= startVolume * Time.deltaTime / FadeTime;
yield return null;
}
audioSource.Stop();
}
}
Thanks mate, this is perfect :)
How would I change the speed of the fade out?
StartCoroutine(AudioController.FadeOut(audioSource, 1f));
Change the float time to something else ins$$anonymous$$d of one. $$anonymous$$ark my comment as the answer please.
Your answer
Follow this Question
Related Questions
Audio won't fade out. 1 Answer
Specific points in audio should trigger events 0 Answers
fade in fade out audio manager 0 Answers
Multiple audio samples on one object. 1 Answer
Help using multiple triggers with multiple scripts. 1 Answer