Is there a way I fade in/out audio in an "if" statement?

The question says it all - I've made an environment where if the player is a certain distance away from an object, an audio clip plays. But I want the audio to fade out and the next audio clip to fade in.

I don't want to use audio software like Audacity because the fade in/out would happen at any point rather than if i am close to the desired object.

Thanks in Advance.

If you have two audiosources and you want to manually crossfade between them, you can do this with a Coroutine.

Something like this (for a linear crossfade):

function Crossfade ( a1 : AudioSource, a2 : AudioSource, duration : float )
    var startTime = Time.time;
    var endTime = startTime + duration;

    while (Time.time < endTime) {

        var i = (Time.time - startTime) / duration;

        a1.volume = (1-i);
        a2.volume = i;



You could then call this function whenever you like to trigger the start of a crossfade from one audiosource to the next.

Unity has a fully-3D capable audio engine. This means it can fade the volume of sounds as you move away from objects automatically. Look at the AudioSource component page, especially the Rolloff property, which lets you set how close you have to be in order for the sound to play.