每次生成随机数,不包括最后一个数字

Lee*_*ong 2 c# random repeat unity-game-engine

我有4种颜色。我想让玩家不能连续 2 次使用相同的颜色。当玩家与物体碰撞时,RandomColor()调用 。所以这个函数在游戏过程中被多次调用,有时玩家不会改变他的颜色。

 using UnityEngine;

 public class ColorManager : MonoBehaviour {

     public SpriteRenderer player;
     public string playerColor;

     public Color[] colors = new Color[4];


     private void Awake()
     {
         RandomColor();        
     }

     public void RandomColor()
     {
         int index = Random.Range(0, 4);

         switch (index)
         {
             case 0:
                 player.color = colors[0]; //colors[0] is orange
                 playerColor = "orange";
                 break;

             case 1:
                 player.color = colors[1]; //colors[1] is pink
                 playerColor = "pink";
                 break;

             case 2:
                 player.color = colors[2]; //colors[2] is blue
                 playerColor = "blue";
                 break;

             case 3:
                 player.color = colors[3]; //colors[3] is purple
                 playerColor = "purple";
                 break;
             }    
     }    
 }
Run Code Online (Sandbox Code Playgroud)

尝试使用while循环,做while循环,但我显然做错了,因为有时我连续两次收到相同的颜色。如果有人弄清楚并解释它是如何/为什么工作的,那就太好了,因为我花了很多时间在这个问题上,而且我很好奇。

Pro*_*mer 5

首先,您需要一个可以生成带排除的随机数的函数。以下是我使用的内容:

int RandomWithExclusion(int min, int max, int exclusion)
{
    int result = UnityEngine.Random.Range(min, max - 1);
    return (result < exclusion) ? result : result + 1;
}
Run Code Online (Sandbox Code Playgroud)

每次调用它时,都需要将结果存储在全局变量中,以便exclusion下次再次调用时将其传递给参数。

我修改了该函数,以便您不必每次调用它时都这样做。新RandomWithExclusion功能将为您做到这一点。

int excludeLastRandNum;
bool firstRun = true;

int RandomWithExclusion(int min, int max)
{
    int result;
    //Don't exclude if this is first run.
    if (firstRun)
    {
        //Generate normal random number
        result = UnityEngine.Random.Range(min, max);
        excludeLastRandNum = result;
        firstRun = false;
        return result;
    }

    //Not first run, exclude last random number with -1 on the max
    result = UnityEngine.Random.Range(min, max - 1);
    //Apply +1 to the result to cancel out that -1 depending on the if statement
    result = (result < excludeLastRandNum) ? result : result + 1;
    excludeLastRandNum = result;
    return result;
}
Run Code Online (Sandbox Code Playgroud)

测试

void Update()
{
    Debug.Log(RandomWithExclusion(0, 4));
}
Run Code Online (Sandbox Code Playgroud)

最后一个数字永远不会出现在下一次函数调用中。

对于您的特定解决方案,只需更换

int index = Random.Range(0, 4);
Run Code Online (Sandbox Code Playgroud)

int index = RandomWithExclusion(0, 4);
Run Code Online (Sandbox Code Playgroud)