Coroutine problem

Hey,

I have an audio manager class that uses pooling to re-use audio clips, i have a method that checks if the clip is already present in the audio sources pool, if so it plays it, else it finds an empty slot to load the clip and play it.

I have a coroutine that stops an audio clip if it is found in the pool, over a period of time, fading it out.

My problem is that i don’t know how to cancel my coroutine if the same clip being faded out needs to be replayed, it will be replayed while continuing to be faded out.

I’m guessing that i have to use “StopCoroutine” but i don’t understand how to do it.

Some help would be appreciated.

public void PlaySound(AudioClip newClip, float newVolume, float newPitch)
    {
        for (int i = 0; i < poolSize; i++)
        {
            //If the clip already exist, we re-use it
            if (audioSources*.clip == newClip)*

{
audioSources*.pitch = newPitch;*
audioSources*.volume = newVolume;*
audioSources*.Play();*
return;
}
}
}

public IEnumerator StopSound(AudioClip newClip, float fadeOutSpeed)
{
for (int i = 0; i < poolSize; i++)
{
//If audio clip is found, stop it with a fade out
if (audioSources*.clip == newClip)*
{
while (audioSources*.volume > 0)*
{
audioSources*.volume -= fadeOutSpeed;*
yield return null;
}
audioSources*.Stop();*
audioSources*.clip = null;*
yield return null;
}
}
}

To use StopCoroutine, you need to save the call to your coroutine method:

// as a variable in the singleton
IEnumerator audio;

// In your method where you start the coroutine
audio = AudioManager.instance.StopSound(someSound, 2);
AudioManager.instance.StartCoroutine(audio);

// and then to cancel/stop that coroutine early
StopCoroutine(audio);