c# - 从调用后我停用的脚本调用协程后如何继续协程
问题描述
我在一个Enamy
附加到游戏对象的类中有一个协程。现在我正在使用 aProjectile
来击中那个敌人并禁用它们。问题是我不想与敌人同时停用弹丸。敌人有一些特殊效果需要在禁用前执行。
为了解决这个问题,我想出了这个:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enamy : MonoBehaviour {
public IEnumerator DestroyEnamy()
{
yield return new WaitForSeconds(1f);
Debug.Log("Execute after 1 second");
gameObject.SetActive(false);
}
}
我想在 Projectile 类中调用协程,而不是在继续协程的同时DestroyEnamy
停用该类。然而,这并没有发生,只有当我保持类启用时才会执行协程,如果我在协程结束之前禁用它会执行协程的第一部分,然后在禁用“Projectile”游戏对象之后,协程也会停止。Projectile
DestroyEnamy
Projectile
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectile : MonoBehaviour
{
private bool firstCollision = false;
private void OnEnable()
{
firstCollision = false;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (!firstCollision)
{
//if the projectile has landed a hit
firstCollision = true;
Transform colliderTransform = collision.transform;
if (colliderTransform.CompareTag("Enamy"))
{
Score.UpdateMainScore(20);
Score.UpdateProjCount(1);
colliderTransform.gameObject.SetActive(false);
}
gameObject.SetActive(false);
}
}
}
解决方案
好吧,不完全确定这是否是您想要的,但您的问题是操作顺序,因此要解决它,您可以将协程包装在另一个函数中并从碰撞对象中获取组件并调用将调用协程的函数
public class test : MonoBehaviour
{
public void CallDestroy ()
{
StartCoroutine (DestroyThis ());
}
public IEnumerator DestroyThis ()
{
yield return new WaitForSeconds (1f);
Debug.Log ("Execute after 1 second");
gameObject.SetActive (false);
}
}
和你这样的弹丸
public class testTwo: MonoBehaviour
{
public void OnCollisionEnter (Collision other)
{
if (other.transform.CompareTag ("Enemy"))
{
other.transform.GetComponent<test> ().CallDestroy ();
this.gameObject.SetActive (false);
}
}
}
尽管您不应该比较标签,而是应该检查该组件是否存在。
if (other.transform.GetComponent<test> () != null)
希望这可以帮助。
推荐阅读
- pandas - 有没有办法用我已经制作的图创建图表网格?
- flutter - 如何让 Paypal 在 Flutter 应用内付款
- mysql - #1241 - 操作数应包含 1 列嵌套查询
- android-studio - Android Studio中黄色和斜体的方法名称是什么意思?
- javascript - 节点 Javascript 类 ReferenceError: X 未定义
- r - GGPLOT2中的字幕
- git - git add 和 git commit 混淆
- javascript - 为什么返回未定义?(免费代码营)
- python - 过滤文件,将文件中的值移动到列表
- c# - 如何在.net核心中获取大括号url值