user8019080
user8019080

Reputation:

Stop coroutine from other script

I am making a game with a maze with audio hints on what way to go. I have the sounds playing on a coroutine and it work in terms of only starting once. However, what I need to do is be able to stop it from another script with a trigger on so that the audio does not keep playing when the player passes a certain point. This is my code so far.

public AudioSource direction;

private bool running = false;

IEnumerator AudioPlay()
{
    while (true)
    {
        direction.Play();

        yield return new WaitForSeconds(2);
    }

}

void OnTriggerEnter(Collider col)
{
    if (col.gameObject.CompareTag("Player"))
    {

        if (running == false)
        {
            StartCoroutine(AudioPlay());

            Debug.Log("Started");

            running = true;
        }

        else if (running == true)
        {
            Debug.Log("Void");
        }

    }           

}

Upvotes: 2

Views: 1765

Answers (1)

Ruzihm
Ruzihm

Reputation: 20259

Use StopCoroutine(previouslyRunCoroutine)

If you use the IEnumerator form (StartCoroutine(AudioPlay());) to start the coroutine, the Unity documentation recommends that you save a reference to the IEnumerator and use that in future calls to StopCoroutine:

public AudioSource direction;

private bool running = false;
public IEnumerator audioPlayCoroutine;

IEnumerator AudioPlay()
{
    while (true)
    {
        direction.Play();

        yield return new WaitForSeconds(2);
    }

}

void OnTriggerEnter(Collider col)
{
    if (col.gameObject.CompareTag("Player"))
    {

        if (running == false)
        {
            audioPlayCoroutine = AudioPlay();

            StartCoroutine(audioPlayCoroutine);

            Debug.Log("Started");

            running = true;
        }

        else if (running == true)
        {
            Debug.Log("Void");
        }

    }           

}

Then, in your other script you can use StopCoroutine:

OtherScript.StopCoroutine(OtherScript.audioPlayCoroutine);

If you were to use the method name form such as StartCoroutine("AudioPlay");, the documentation would recommend using the method name form to stop it:

OtherScript.StopCoroutine("AudioPlay");

Upvotes: 2

Related Questions