Random.Range选两个号码,如果相同,选一个新号码

Random.Range picking two numbers, if the same, pick one new

我正在挑选 sprite 并将它们放在彼此之上,我是通过从数组中随机挑选它们来做到这一点的。 为了给人一种不重复的错觉,关键是它们不一样。

如何在不添加到我的数组的情况下实现这一点,从而将我的索引放在数组边界之外?`

  //Random Sprite Value
    int bloodSprite  = Random.Range(0, 12);
    int bloodSprite2 = Random.Range(0, 12);

    if (bloodSprite == bloodSprite2)
    {
        // what do I write here? (if here)
    }

它应该适合你。

while(bloodSprite == bloodSprite2)
{
   bloodSprite2 = Random.Range(0, 12);
}

警告:出现无限循环的可能性非常低。

do.. while 在这里会有帮助

//Initialize default value to bloodSprite and bloodSprite2
int bloodSprite = int.MinValue;
int bloodSprite2 = int.MinValue;
do
{
    //Random Sprite Value
    bloodSprite  = Random.Range(0, 12);
    bloodSprite2 = Random.Range(0, 12);
    //At the end, check condition in while.
}while(bloodSprite == bloodSprite2);

int.MinValue : 常量表示整数的最小可能值。

在上面的解决方案中,我们将 int 的最小可能值定义为 bloodSprit,它将在 do..while() 循环

中更新它

为什么我们使用 do..while() 循环?

  • do..while 循环首先执行代码并在循环结束时检查条件。这允许我们在 do..while 循环中至少执行一次代码。

流程图:

首先从 0 到 12 中随机取一个 x,然后从 0 到 x - 1 或从 x + 1 到 12 中随机取一个。你可以选择任何一个。

int s1 = Random.Range(0, 12);
int s2 = s1 == 0 ? Random.Range(s1, 12) : Random.Range(0, s1);

你真的不需要循环。