繁体   English   中英

从调用后停用的脚本中调用协程后如何继续

[英]How can I continue Coroutine after calling it from a script that I deactivated after that call

我在与Enamy对象相连的Enamy类中有一个协程。 现在,我正在使用Projectile击中该敌人并将其禁用。 问题是我不想与敌人同时停用弹丸。 敌人有一些特殊效果,需要在禁用之前执行。

为了解决这个问题,我想出了这个:

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

我想在抛射类中调用DestroyEnamy协程,而不是在继续继续DestroyEnamy协程的同时停用Projectile类。 但是这没有发生,只有在我保持Projectile类启用的情况下,协程才会执行,如果在协程结束之前禁用它,它将执行协程的第一部分,然后在取消“ Projectile” gameObject之后,协程也会停止。

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)

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM