Volume Fade Out

Hey guys,

I know this has been asked before, but I havent been able to find a good answer yet. I am trying to fade out my audio once I release the move button. So far I have:

if(Input.GetKey(moveRight) || Input.GetKey(moveLeft))
	{
		animator.SetBool("Move", true);
			if(!audio.isPlaying)
				{
					audio.Play();
				}
	}
else
	{
		for(var vol = 1; vol >=0; vol -= 0.1)
			{
				audio.volume = vol;
			}
	}

However, this last part essentially crashes unity. Is there a better way to fade out audio?

You want to approach this by doing a bit of work each update call. Something like:

float av = audio.volume - speed * Time.deltaTime;
if (av < 0.0) av = 0;
audio.volume = av;

‘speed’ is a float you define at the top of the file. It will be how much to lower the volume per second.