如何在Unity中为for循环应用间隔/延迟

时间:2019-05-09 02:07:08

标签: c# unity3d

我正在尝试以for循环中生成的1-3随机数开始我的场景。

我希望每次都随机生成一个数字,但是我不希望彼此直接直接生成相同的两个数字,而是先生成一个介于1-3之间的随机数字,然后等待60秒,会生成1-3之间的随机数(不包括最近生成的数字)。

S3

Edit 尝试实现一个协同例程以充当循环的间隔。但是,它仍然无法正常工作,它可以打印到控制台,因此可以肯定地执行了该例程,但是WaitForSeconds函数似乎不起作用。

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

    }
}

4 个答案:

答案 0 :(得分:2)

  1. 启动方法可以是协程,因此将返回类型更改为yield return new WaitForSeconds(60);

  2. 在for循环的末尾添加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); } }

sqlalchemy

答案 1 :(得分:1)

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

答案 2 :(得分:0)

从性能的角度改进shingo的回答(我不喜欢while循环,因为即使它最终会结束,它也只能概率性地结合到最坏的情况^^。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);
    }
}

答案 3 :(得分:0)

好吧,我将自己的名字放在“不是最后一项”上,可以简单地解决递归过程。

private int currentValue = -1;
private List<int> list = new List<int>(){ 0, 1, 2 };
void Start()
{
     // Set current value
     this.currentValue = this.list[Random.Range(0, this.list.Count)];
     // invoke SetValue in 60 seconds
     Invoke("SetValue", 60f);
}

void SetValue()
{
     // store current value
     int temp = this.currentValue;
     // remove current value so it can't be picked
     this.list.Remove(temp);
     // set a new value, current value cannot be picked since it got removed
     this.currentValue = this.list[Random.Range(0, this.list.Count)];
     // current value is set, previous value is pushed back in the list
     this.list.Add(temp);
     // invoke SetValue in 60 seconds
     Invoke("SetValue", 60f);
}
void OnDestroy()
{
     // object is destroyed (could be OnDisable), remove the invoke
     CancelInvoke("SetValue");
}