从其他脚本停止协程

时间:2019-06-10 15:57:13

标签: c# unity3d coroutine

我正在用迷宫制作游戏,并带有声音提示如何走。我在协程上播放声音,并且只能启动一次。但是,我需要做的是能够在打开触发器的情况下从另一个脚本中停止它,以便当播放器经过某个点时音频不会继续播放。到目前为止,这是我的代码。

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");
        }

    }           

}

1 个答案:

答案 0 :(得分:1)

使用StopCoroutine(previouslyRunCoroutine)

如果您使用IEnumerator表单(StartCoroutine(AudioPlay());)启动协程,则Unity文档recommends将保存对IEnumerator的引用并在以后使用致电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");
        }

    }           

}

然后,在其他脚本中,您可以使用StopCoroutine

OtherScript.StopCoroutine(OtherScript.audioPlayCoroutine);

如果要使用诸如StartCoroutine("AudioPlay");之类的方法名形式,则文档建议使用方法名形式来停止它:

OtherScript.StopCoroutine("AudioPlay");
相关问题