如何从另一个脚本中停止Coroutine?
我想通过从另一个单独的脚本引用以下脚本中的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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
立即通过其他脚本停止Coroutine的一种方法是使用
stopCoroutine
。为此,您必须首先将Coroutine存储在变量中。停止方法还可以如下。
在下一步中,足以从另一个脚本或同一脚本本身访问停止方法。
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.The stop method also works as follows.
In the next step, it is enough to get access to the stop method from another script or the same script itself.