Hi,
So, I’ve made a script where whenever the player’s character gets added, the script will gets a random fruit and put it into the player’s backpack.
But whenever I run the code, it says "invalid argument #1 to ‘random’ (interval is empty)" Line 14
I’ve tried printing the data.Weight value and it give me the correct number, but when I try printing the sum value it just says the default value given.
Here’s the main code:
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerStorage = game:GetService("ServerStorage")
local Players = game:GetService("Players")
local fruitsData = require(ReplicatedStorage.FruitsData)
local fruits = ServerStorage.Fruits:GetChildren()
-- Gets a random fruit and returns an id to access the specific fruit
local function getRandomFruit()
local sum = 0
for id, data in ipairs(fruitsData) do
sum += data.Weight
end
local rng = math.random(sum) -- Break point
for id, data in ipairs(fruitsData) do
if rng <= data.Weight then
return id
else
rng -= data.Weight
end
end
end
Players.PlayerAdded:Connect(function(plr)
print(plr.Name.." has joined the game!")
plr.CharacterAdded:Connect(function()
print(plr.Name.." spawned")
local fruitId = getRandomFruit()
if not fruitId then warn("Couldn't get fruitId") return end
-- Access the fruit data with the id
local newFruit = fruitsData[fruitId]
for _, fruit in ipairs(fruits) do
if fruit.Name:match(newFruit.Name) then
local newfruit = fruit:Clone()
newfruit.Parent = plr.Backpack
print(newfruit.Name.." has been added to "..plr.Name.." with the weight of "..newFruit.Weight)
continue
else return
end
end
end)
end)
FruitsData code:
return {
[0.1] = {Name="GenoFruit",Weight=99};
[0.2] = {Name="HarukoFruit",Weight=1}
}
Everything is appreciated!