【问题标题】:Stop coroutine from other script从其他脚本停止协程
【发布时间】:2019-06-10 15:57:13
【问题描述】:

我正在制作一个带有迷宫的游戏,并带有关于要走什么路的音频提示。我在协程上播放声音,它只启动一次。但是,我需要做的是能够通过触发器从另一个脚本中阻止它,以便在播放器通过某个点时音频不会继续播放。这是我目前的代码。

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

    }           

}

【问题讨论】:

  • 试过StopCoroutine(AudioPlay())?
  • 您可以在主脚本中添加一个函数来停止协程,然后从其他脚本中调用它。

标签: c# unity3d coroutine


【解决方案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");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-24
    • 2011-12-26
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多