使Random.range不重复值

Viv*_*egi 2 c# unity-game-engine

我必须产生不同的对象,重要的是没有两个对象重复.我的意思是,random.range不应该同时获得两个相同的数字,否则代码有时产生相同的对象.这是一个更简单的代码,可以帮助您了解我正在尝试的内容.

void Update () {

    j = Random.Range (1, 4); // this should give j values like=(1,2,1,3,2,1)
                              // and not this = (1,1,2,2...) the numbers should not repeat simultaneously.

    Inst();
}

void Inst(){

    if (j == 1) {

        //instantiate obj1
    }
    else if (j == 2) {

        instantiate obj2
    }

    else if (j == 3) {

        instantiate obj3
    }


}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Nik*_*wal 5

怎么样

int lastValue;
public int UniqueRandomInt(int min, int max)
{
    int val = Random.Range(min, max);
    while(lastValue == val)
    {
        val = Random.Range(min, max);
    }
    lastValue = val;
    return val;
}

void Update() 
{
    UniqueRandomInt(1, 4);
    Inst();
}

void Inst()
{
    if (lastValue == 1)
    {
        //instantiate obj1
    }
    else if (lastValue == 2)
    {
        //instantiate obj2
    }
    else if (lastValue == 3)
    {
        //instantiate obj3
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我不知道为什么会有这么多的赞成票.它可能导致许多严重的问题,所以这样的游戏冻结甚至锁定.不要使用随机数来控制`while`循环,除非你在协程函数中等待一些帧. (2认同)