如何在 Unity 中对 for 循环应用间隔/延迟 [英] How to apply an interval/ delay to a for loop in Unity
问题描述
我试图以在 for 循环中生成的 1-3 随机数开始我的场景.
I'm attempting to begin my scene with a random number from 1-3 being generated in a for loop.
我打算每次都是随机数,但是我不想在彼此之后直接生成相同的两个数字,而是首先生成一个 1-3 之间的随机数,然后等待 60 秒,生成一个 1-3 之间的随机数,不包括最近生成的数.
I intend for the number to be random each time, however i don't wan't the same two numbers to be generated directly after each other, instead firstly generating a random number between 1-3, then waiting 60 seconds, generating a random number between 1-3 excluding the most recently generated number.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KOTH_ZoneRandom : MonoBehaviour
{
int Rand;
int Lenght = 4;
List<int> list = new List<int>();
void Start()
{
list = new List<int>(new int[Lenght]);
for (int j = 1; j < Lenght; j++)
{
Rand = Random.Range(1, 4);
while (list.Contains(Rand))
{
Rand = Random.Range(1, 4);
}
list[j] = Rand;
print(list[j]);
}
}
}
Edit 尝试实现一个协同程序来充当循环的间隔.但是它仍然不起作用,它打印到控制台,因此协程肯定正在执行,但是 WaitForSeconds 函数似乎不起作用.
Edit attempted to implement a co-routine to act as an interval for the loop. however it's still not working, its prints to the console so the co-routine is definitely being executed, however the WaitForSeconds function doesn't seem to be working.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KOTH_ZoneRandom : MonoBehaviour
{
int Rand;
int Length = 4;
List<int> list = new List<int>();
void Start()
{
list = new List<int>(new int[Length]);
for (int j = 1; j < Length; j++)
{
StartCoroutine(loopDelay());
Rand = Random.Range(1, 4);
while (list.Contains(Rand))
{
Rand = Random.Range(1, 4);
}
list[j] = Rand;
print(list[j]);
}
}
IEnumerator loopDelay ()
{
print("started delay");
yield return new WaitForSeconds(60);
}
}
推荐答案
Start 方法可以是协程,因此将返回类型更改为
IEnumerator
.
在for循环的末尾添加yield return new WaitForSeconds(60);
.
Add yield return new WaitForSeconds(60);
at the end of for loop.
IEnumerator Start()
{
list = new List<int>(new int[Lenght]);
for (int j = 1; j < Lenght; j++)
{
Rand = Random.Range(1, 4);
while (list.Contains(Rand))
{
Rand = Random.Range(1, 4);
}
list[j] = Rand;
print(list[j]);
yield return new WaitForSeconds(60);
}
}
这篇关于如何在 Unity 中对 for 循环应用间隔/延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!