WaitforSeconds没有完全等待Unity中指定的时间

本文关键字:时间 Unity 等待 WaitforSeconds | 更新日期: 2023-09-27 17:59:22

我使用WaitforSeconds进行搜索,并按照前面提到的方式使用(使用IEnumeration的返回类型,使用协程而不是更新)。但它没有起作用。最初,它显示WaitforSeconds和IEnumerator不"存在于当前上下文中"。我不得不重新安装团结来修复它,但这个问题仍然存在。以下是我的代码。我使用WaitforSeconds的方式正确吗?是"if"代码块破坏了我的完整工作吗(我的意思是我用错地方了吗)?

using UnityEngine;
using System.Collections;
public class EnemyCreeator : MonoBehaviour 
{
    public float xmin,xmax,zmin,zmax;
    public GameObject enemy;
    public float spawnWait,StartWait,waveWait;
    public int turretCount;
    public int enemyCount;
    int i=0;
    void Update() 
    {
        StartCoroutine (TurretWaves());
    }
    IEnumerator TurretWaves()
    {
        while (true) 
        {  
            Vector3 pos=new Vector3(Random.Range (xmin,xmax),0.5f,Random.Range(zmin,zmax));
            yield return new WaitForSeconds(StartWait);
            while(i<turretCount) 
            {
                //Debug.Log ("The vaue of game time in spawnwaiting is: "+Time.time);
                Instantiate (enemy, pos, Quaternion.identity);
                enemyCount++;
                i++;
                //Debug.Log ("value of i in loop is: "+i);
                //Debug.Log ("The vaue of game time is: "+Time.time);
                yield return new WaitForSeconds (spawnWait);
            }
            //Debug.Log("cHECKing Before WAVE WAIT(value of time )is: "+Time.time);
            yield return new WaitForSeconds(waveWait);
            if(i>=turretCount)
            {
                i=0;
            }
            //Debug.Log("cHECKing AFTER WAVE WAIT and value of time is: "+Time.time);
            //Debug.Log ("value of i outside the while loop is: "+i);
        }
    }
}

代码需要等到生成每个炮塔之前等待,并在生成下一波之前等待。即使Startwait运行良好,我仍然找不到其他人的问题。。。

提前谢谢。

WaitforSeconds没有完全等待Unity中指定的时间

您的代码是正确的,除了

void Update()
{
    StartCoroutine (TurretWaves());
}

通过这样做,您将在的每一帧中创建一个新的协同程序。因此,在Startwait秒后,每个运行的协同程序都会在以下帧中产生一个敌人,从而使整个脚本无法正常工作。但事实上,每一次协同工作都如你所料。

要解决您的问题,请更改

void Update()

void Awake()

void Start()

从而只启动一个协同程序。它应该按预期工作。

编辑#1:

我想你误解了协同程序在Unity中的工作方式,因为你似乎在使用Update逐帧手动执行协同程序中的代码。

当协同程序由StartCoroutine启动时,一个"任务"将在Unity中注册。这个任务就像另一个线程(只是它仍然在主线程中)。Unity将自动执行此任务中的代码。当遇到yield语句时,它会暂停并等待该语句结束。(在内部,它会持续检查状态,并确定何时恢复。)例如,yield return new WaitForSeconds(n)会使Unity在n秒内暂时停止执行协程中的代码。在那之后,它将继续。

该任务将被注销,直到不再执行任何代码(在您的情况下,由于while循环,它永远不会结束),或者启动协同程序的游戏对象被销毁或停用。