我正在尝试以for循环中生成1-3的随机数开始我的场景。
我打算每次是随机的,但是我不是直接在彼此之后直接生成的两个数字,而是首先生成1-3之间的随机数,然后等待60秒,在不包括最近生成的数字的1-3之间生成一个随机数。
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功能似乎无法正常工作。
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);
}
}
-
启动方法可以是coroutine,因此将返回类型更改为
IEnumerator
。 -
在循环的末尾添加
yield return new WaitForSeconds(60);
。
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);
}
}
void start() {
StartCoroutine(KothTimer());
}
IEnumerator KothTimer() {
var wait = new WaitForSeconds(HillSwitchDelay);
while(enabled) {
var chosenHill = ListOfHills[Random.Range(0, ListOfHills.count)];
SetActiveHill(chosenHill);
yield return wait;
}
}
从性能的角度来改进Shingo的答案(我在循环时不喜欢这个,因为即使它最终结束,它也只能绑定到最坏情况下的情况 ^^。ofc它起作用,这只是丑陋(:
using System.Linq;
void start()
{
StartCoroutine(KothTimer());
}
IEnumerator KothTimer()
{
System.Random rnd= new System.Random();
var oneToFourShuffled = (new int[4]{1,2,3,4}).OrderBy(x => rnd.Next()).ToArray();
for (int j = 0; j < Length; j++)
{
list[j] = oneToFourShuffled[j];
print(list[j]);
yield return new WaitForSeconds(60);
}
}