如何从另一个脚本中停止Coroutine?

发布于 2025-02-04 04:46:36 字数 702 浏览 2 评论 0原文

我想通过从另一个单独的脚本引用以下脚本中的Coroutine“ Spawn”。我应该怎么做?

public class spawnerAlt : MonoBehaviour
{
    public IEnumerator Spawn;
    private void Start()
    {
        Spawn = delayedSpawn();
        StartCoroutine(Spawn);
    }

    public IEnumerator delayedSpawn()
    {
        while (true)
        {
            spawn();
            yield return new WaitForSeconds(delay);
        }
    }

    void spawn()
    {
        Rigidbody2D clone;
        clone = Instantiate(toSpawn, new Vector2(8.39f,Random.Range(upperBound,lowerBound)), transform.rotation);
        clone.velocity = transform.TransformDirection(Vector2.left * speed);
    }
}

I want to stop the coroutine "spawn" in the following script by referencing it from another separate script. How should I go about doing that?

public class spawnerAlt : MonoBehaviour
{
    public IEnumerator Spawn;
    private void Start()
    {
        Spawn = delayedSpawn();
        StartCoroutine(Spawn);
    }

    public IEnumerator delayedSpawn()
    {
        while (true)
        {
            spawn();
            yield return new WaitForSeconds(delay);
        }
    }

    void spawn()
    {
        Rigidbody2D clone;
        clone = Instantiate(toSpawn, new Vector2(8.39f,Random.Range(upperBound,lowerBound)), transform.rotation);
        clone.velocity = transform.TransformDirection(Vector2.left * speed);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

疯狂的代价 2025-02-11 04:46:36

立即通过其他脚本停止Coroutine的一种方法是使用stopCoroutine。为此,您必须首先将Coroutine存储在变量中。

public Coroutine spawnCoroutine;

private void Start()
{
    spawnCoroutine = StartCoroutine(delayedSpawn());
}

停止方法还可以如下。

public void StopSpawn() => StopCoroutine(spawnCoroutine);

在下一步中,足以从另一个脚本或同一脚本本身访问停止方法。

public void AnotherScriptMethod()
{
    FindObjectOfType<spawnerAlt>().StopSpawn(); // for E.G
}

One way to stop coroutine immediately through other scripts is to use StopCoroutine. To do this, you must first store your coroutine in a variable.

public Coroutine spawnCoroutine;

private void Start()
{
    spawnCoroutine = StartCoroutine(delayedSpawn());
}

The stop method also works as follows.

public void StopSpawn() => StopCoroutine(spawnCoroutine);

In the next step, it is enough to get access to the stop method from another script or the same script itself.

public void AnotherScriptMethod()
{
    FindObjectOfType<spawnerAlt>().StopSpawn(); // for E.G
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文