Fading Audio in/out with object creation

Hello,

I’m trying, as the title strongly suggests, to fade audio in and out based in the creation of an object. I’ve got the fading down and working when attached to a couple of keys, but when i try calling the function based on object tags i get some odd results. I think it’s to do with the update constantly resetting the fade, because it sounds glitchy, but i’m just stumped as to what to do now, i’ve been churning my noob brain around for hours.

I’d love some help.

Thanks.

    function Update () {

var proxies = GameObject.FindGameObjectsWithTag("Proxy").Length;


	if (proxies > 0){

	FadeInSound();
	
}

	if (proxies <= 0){

	FadeOutSound();
	}	
}

		
var menuMusic:GameObject;


function FadeOutSound(){
   
    if (menuMusic) {
       
        for (var i = 99; i > 0; i--){
          menuMusic.audio.volume = i * .01;
          yield new WaitForSeconds (.015);
          print ("Fading Out...");
        }
        menuMusic.audio.volume = 0;
    }
}

function FadeInSound(){
   
    if (menuMusic) {
       
        for (var i = 1; i < 99; i++){
          menuMusic.audio.volume = i * .01;
          yield new WaitForSeconds (.015);
          print ("Fading In...");
        }
        menuMusic.audio.volume = 1;
    }
}

This problem probably is caused by a coroutine being called multiple times. When you call a coroutine (any routine containing yield) it creates an instance which will run in the background until it ends. If you call this coroutine again, another instance will be created, and in the code above the new instance will “fight” with the others already running for the volume control.

You could improve your code and solve this problem using this:

private var proxy = false;
private var lastProxy = false;

function Update(){

    if (GameObject.FindWithTag("Proxy")){ // if any Proxy object exists...
        proxy = true; // set proxy flag true
    }
    else {
        proxy = false; // else set it false
    }
    if (proxy != lastProxy){ // if proxy changed state...
        lastProxy = proxy;
        if (proxy){ // and a new Proxy object was found...
            StopCoroutine("FadeOutSound"); // stop FadeOut coroutine (if any)
            FadeInSound(); // and start FadeIn
        } 
        else { // but if no more Proxy objects exist...
            StopCoroutine("FadeInSound"); // stop FadeIn coroutine (if any)
            FadeOutSound(); // and start FadeOut
        }
    }
}

function FadeOutSound(){

    if (menuMusic) {
        for (var i = 99; i > 0; i--){
          menuMusic.audio.volume = i * .01;
          yield new WaitForSeconds (.015);
          print ("Fading Out...");
        }
        menuMusic.audio.volume = 0;
    }
}

function FadeInSound(){

    if (menuMusic) {
        for (var i = 1; i < 99; i++){
          menuMusic.audio.volume = i * .01;
          yield new WaitForSeconds (.015);
          print ("Fading In...");
        }
        menuMusic.audio.volume = 1;
    }
}