- Home /
Audio fade out problem
Hi everyone, I tried to make an audio fade out to my clip, but i don't understand why this code dosn't work. Thanks in advance.
#pragma strict
var Allarme : AudioClip;
var audio1Volume : float = 1.0;
function Start () {
}
function Update () {
if (Input.GetKeyDown (KeyCode.H)) {
audio.clip = Allarme;
audio.Play();
audio.loop = true;
}
else if (Input.GetKeyUp (KeyCode.H)) {
audio.clip = Allarme;
audio.Stop();
fadeOut();
}
}
function fadeOut() {
if(audio1Volume > 0.1)
{
audio1Volume -= 0.1 * Time.deltaTime;
audio.volume = audio1Volume;
}
}
Input.Get$$anonymous$$eyUp ($$anonymous$$eyCode.H) is only true for one frame so your fadeOut method will only be called once, as well as that you call audio.Stop(); which will stop playing the audio immediately, try the following:
var Allarme : AudioClip;
var audio1Volume : float = 1.0;
function Update () {
if(Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.H)) {
audio.clip = Allarme;
audio.Play();
audio.loop = true;
}
if(!Input.Get$$anonymous$$ey($$anonymous$$eyCode.H)) {
fadeOut();
}
}
function fadeOut() {
if(audio1Volume > 0){
audio1Volume -= 0.1 * Time.deltaTime;
audio.volume = audio1Volume;
}else{
audio1Volume = 0;
audio.volume = audio1Volume;
}
}
This is untested I'm afraid as I'm away from my main computer, you could also do this by having a boolean variable to define when to start fading out but I'm unsure which would be more efficient.
this works only one time that i press H, if after i press H again, the audioclip don't hear anymore.
ahh yeah, forgot to reset the volume again when pressing H, just add in setting the volume back to 1 in the first if statement
Answer by fafase · Apr 12, 2014 at 03:21 PM
You need to use a coroutine. Your code only calls the method once and then wait for another press and each a tiny bit is happening.
function fadeOut(){
while(audio.volume > 0){
audio.volume -= Time.deltaTime;
yield;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613142542im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Smooth GUI and Audio Volume Fades 5 Answers
Fading Audio in/out with object creation 1 Answer
Unity crashes when it tries to play a sound! 1 Answer
Audio Fade With Toggle 0 Answers
Help with Audio Fade 2 Answers