簡體   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