使用百分比/概率在 Unity 中生成随机游戏对象

问题描述

所以我有 4 个当前随机生成的游戏对象。

1.正规平台 2.尖刺平台 3.Bouncy平台 4.币平台

所以问题是它是随机生成的。 问题 如何添加或控制每个平台的生成概率。代码明智。 C#

比如在播放时间的 10 秒内。 85% 几率生成普通平台 5% 几率生成尖刺平台 5% 的几率产生弹性平台 5% 几率生成币平台

请注意,该平台在游戏中每秒钟都会生成一次。

解决方法

你可以这样做。

/// <summary>
/// Returns random index of a finite probability distribution array
/// </summary>
/// <param name="prob"></param>
/// <returns></returns>
public static int PickOne(float[] prob)
{
    int index = 0;
    float r = UnityEngine.Random.value;

    while (r > 0)
    {
        r -= prob[index];
        index++;
    }
    index--;

    return index;
}

这会根据带有最终支持的概率分布为您提供随机索引。所以如果你打电话

int index = PickOne(new float[] { 0.85f,0.05f,0.05f });

index 将是基于您提供的概率分布的随机索引值(在这​​种情况下,介于 0 和 3 之间)。