簡體   English   中英

IEnumerator 腳本不工作並且協程沒有運行? 團結,C#

[英]IEnumerator script is not working and Coroutine is not running? Unity,C#

我正在為我的游戲中的 Enemy 編寫一個腳本,他們將在一定的時間間隔使用 Coroutine 攻擊英雄。 雖然,在運行游戲時,敵人並沒有攻擊。 我為敵人 animation 創建了兩個事件,專門用於攻擊。 代碼的 IE 分子部分未運行。 誰能告訴我出了什么問題?

我編寫了 Debug.Log("Hello"),以驗證它是否執行但不打印。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAttack : MonoBehaviour
{
    [SerializeField] private float range = 3f;
    [SerializeField] private float timeBetweenAttacks = 1f;

    private Animator anim;
    private GameObject player;
    private bool playerInRange;
    private BoxCollider[] weaponColliders;

    // Start is called before the first frame update
    void Start()
    {
        weaponColliders = GetComponentInChildren <BoxCollider[]> ();
        player = GameManager.instance.Player;        
        anim = GetComponent <Animator> ();
        StartCoroutine (attack());
    }

    // Update is called once per frame
    void Update()
    {
        if(Vector3.Distance(transform.position,GameManager.instance.Player.transform.position) < range)
        {
            playerInRange = true;
        }else{
           playerInRange = false;
        }
        
    }

    public IEnumerator attack()
    {
        Debug.Log("Hello");
        if(playerInRange && !GameManager.instance.GameOver)
        {
            anim.Play("Attack");
            yield return new WaitForSeconds(timeBetweenAttacks);
        }
        yield return null;
        StartCoroutine(attack());        
    }

    public void EnemyBeginAttack(){
        foreach(var weapon in weaponColliders){
            weapon.enabled = true;
        }
    }

    public void EnemyEndAttack(){
        foreach(var weapon in weaponColliders){
            weapon.enabled = false;
        }
    }
}

問題可能是代碼weaponColliders = GetComponentInChildren<BoxCollider[]>(); . GetComponentInChildren 只能用組件類型(或接口類型)調用,但BoxCollider[]是一個數組類型。

您應該改用GetComponentsInChildren<BoxCollider>(); .

我試着寫BoxCollider weaponColliders = GetComponentInChildren <BoxCollider> (); 然后錯誤消失了。 任何原因?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM