StopCoroutine is not working?

Hi,

I’m using this code for my buttons:

var action = "action";

function OnMouseDown () {
	StartCoroutine(action);
}

function Demo () {
	audio.Play();
}

function Stop () {
	StopCoroutine("Demo");
}

When I click the button with the action, “Demo” it works fine but when I click the button with the action “Stop” the Demo coroutine doesn’t stop?

Does anybody know why this is?

Thanks,
Stuart

It looks as though it should work. Are you getting any error messages? If not, try putting a print statement in the Stop method, just to make sure it is getting called when you think it is.

Do you have real code?
Above code will not work anyway, as you start function action but try to stop function Demo

Hi,

Yes I’ve tested the demo function and it is getting started.

Real Code? I’m not calling “action” because I change the variable within Unity to “demo”

Thanks,
Stuart

I’m not sure how JS works, but if this was written in C#, i believe the script would stop running. It wouldn’t work because there is no “action” function, and therefore there is no coroutine to start.

This is closer to the correct code. I don’t know much JS, but I think this should work.

var action = "Demo"; 

function OnMouseDown () { 
   StartCoroutine(action); 
} 

function OnMouseUp() { Stop(); }

function Demo () { 
   audio.Play(); 
} 

function Stop () { 
   StopCoroutine("Demo"); 
}

your other option could be this:

var action = "Demo"; 

function OnMouseDown () { 
   StartCoroutine(action); 
} 

function OnMouseUp() { Stop(); } 

function Demo () { 
   audio.Play(); 
yield break;
} 

function Stop () { 
   StopCoroutine(action); 
}

Well I should reformulate the question: In the current code, StopCoroutine is pointless because there will be no coroutine to stop. Demo enters, starts the sounds and immediately leaves again. Thats why I asked for the real code.

Am I right to assume that you missbelieve that stopping the Demo coroutine, even if it would still be running, would anyway impact the sound?
If so then you are wrong :slight_smile:
The right thing to do would be stopping the audio again in Stop :slight_smile:

:o I see what you mean now, I get it. I’ll try that now.

Thanks a lot,
Stuart