How to make balls genuienly have their spawn rate

hi some im making a game abt balls. they all have different abilities to play around with and yeah. i also wanted rarities for the game:

local max = 0
for i, v in pairs(ballsFolder:GetChildren()) do
    if v:FindFirstChild("Percentage") then
        max = max + v.Percentage.Value
    end
end
print(max)

local function getRandomBall()
    local randomValue = math.random() * max
    print(randomValue)
    local cumulativeProbability = 0

    for _, ball in ipairs(balls) do
        local percentage = ball:FindFirstChild("Percentage") and ball.Percentage.Value or 0
        cumulativeProbability = cumulativeProbability + percentage
        if randomValue <= cumulativeProbability then
            return ball
        end
    end
end

heres the thing: i made multiple balls have like “[x]% spawn rate” and stuff, and like max just doesnt equal to 100. so i thought making max be all the percentages together would fix it. thats until, for testing purposes, i put a ball spawn rate at 100%. other balls were still spawning.

im trying to figure out how a ball with a [x]% spawn rate ACTUALLY has a [x]% chance of spawning.
plz help :smiley:

Unless your values all add up to 100%, then you won’t be able to have exact spawn chances. By setting a value to 100%, without setting all others to 0%, then you cause the values to add up to more than 100%, which prevents it from working correctly.

So yeah, the only way to achieve what you want is to have all the values add up to 100% exactly.

1 Like