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

时间:2017-12-25 12:06:54

标签: c# unity3d random repeat

我有4种颜色。我想这样做,以便玩家可以连续两次使用相同的颜色。当玩家与对象发生碰撞时,会调用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;
             }    
     }    
 }

尝试使用while循环,执行while循环,但我显然做错了,因为我有时会连续两次收到相同的颜色。如果有人弄清楚并解释它是如何/为什么有效的话会很棒,因为我在这个问题上度过了很长一段时间而我非常好奇。

2 个答案:

答案 0 :(得分:3)

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

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

每次调用它时,都需要将结果存储在全局变量中,以便下次再次调用时将其传递给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;
}

<强>测试

void Update()
{
    Debug.Log(RandomWithExclusion(0, 4));
}

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

对于您的具体解决方案,只需替换

即可
int index = Random.Range(0, 4);

int index = RandomWithExclusion(0, 4);

答案 1 :(得分:0)

如果RandomColor返回与上一个颜色相同的颜色,您需要做的是添加一个判断,只需再次调用它,对吗?

相关问题