作者:幻世界 

 

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

Unity随机概率扩展(概率可调控)_.net

一.做加法
 

   /**加*/
    //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随机概率扩展(概率可调控)_数组_02