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

时间:2015-06-23 22:27:09

标签: c# unity3d ienumerator

我搜索了使用WaitforSeconds并按原样使用(使用返回类型的IEnumeration并使用协程而不是更新)。但它不起作用。最初它显示Waitfor Seconds和IEnumerator不在当前上下文中出现"。我不得不重新安装统一来修复它,但这个问题仍然存在。以下是我的代码。我是否以正确的方式使用WaitforSeconds?这是'如果'破坏我完整工作的代码块(我的意思是我在错误的地方使用过它)?

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

代码需要等到spawnWait才产生每个炮塔并等到wavewait生成下一个wave。即使Startwait工作正常,我仍然无法找到其他人的问题......

提前致谢。

1 个答案:

答案 0 :(得分:2)

您的代码是正确的,但

除外
df_attachment['Duplicate'] = df_attachment.duplicated('LowerFileName', keep=False)

通过这样做,您将在每一帧中创建一个新的协同程序。因此,在 Startwait 秒之后,每个运行的协同程序将在以下帧中生成一个敌人,使整个脚本无法正常工作。但事实上,每个协程都按预期工作。

要解决您的问题,请更改

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

void Update()

void Awake()

这样只启动了一个协程。它应该按预期工作。

编辑#1:

我认为你误解了协同程序中的协同程序是如何工作的,因为你似乎正在使用void Start() 逐帧手动执行协程内的代码。

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

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

相关问题