做了以下两张图有助于理解,如果想调控概率的话直接修改概率数组即可

其实在做概率类相关的界面效果的时候,我们真实做法都是在刷新界面前已经把结果获取到了,然后根据结果去处理界面上的逻辑,一定要带着这个思想去理解以下内容 

【Unity开发小技巧】Unity随机概率扩展(概率可调控)_概率

一.做加法

/**加*/
//rate:几率数组(%), total:几率总和(100%)
// Debug.Log(rand(new int[] { 10, 5, 15, 20, 30, 5, 5,10 }, 100));
public static int rand(int[] rate, int total)
{
int r = Random.Range(1, total+1);
int t = 0;
for (int i = 0; i < rate.Length; i++)
{
t += rate[i];
if (r < t)
{
return i;
}
}
return 0;
}

二.做减法

/**减*/
//rate:几率数组(%), total:几率总和(100%)
// Debug.Log(randRate(new int[] { 10, 5, 15, 20, 30, 5, 5,10 }, 100));
public static int randRate(int[] rate, int total)
{
int rand = Random.Range(0, total+1);
for (int i = 0; i < rate.Length; i++)
{
rand -= rate[i];
if (rand <= 0)
{
return i;
}
}
return 0;
}

运行100次的结果:

【Unity开发小技巧】Unity随机概率扩展(概率可调控)_数组_02