I'm trying to make a script where it spawns items into a part who's parent is a folder with a rarity system, but keeps repeating the same strings. Is there another way to do this?
These are the items v
local Items = { {"Ikea Spell Book",1}, {"Baguette Sword",1}, {"Plant",10}, {"Axe",10}, {"Knife",10}, {"Makeshift Spear",10}, {"Angle Grinder",10}, }
Counts all the numbers in the table and adds it into TotalWeight
local TotalWeight = 0 for _,ItemData in pairs(Items) do TotalWeight = TotalWeight + ItemData[2] end
Now we add it into the second function of math.random and then checks if the chance is lower or equal to Counter and if it is it returns the string
local function chooseRandomItem() local Chance = math.random(1,TotalWeight) local Counter = 0 for _,ItemData in pairs(Items) do Counter = Counter + ItemData[2] if Chance <= Counter then return ItemData[1] end end end
Now for the for loop that causes all of this
for _,v in pairs(script.Parent:GetChildren()) do if v:IsA("BasePart") then if not v:FindFirstChildOfClass("Model") then local RandomItem = chooseRandomItem() local clone = game.ServerStorage.Pickups:FindFirstChild(RandomItem):Clone() clone:SetPrimaryPartCFrame(v.CFrame) clone.Parent = v -- Clone, CFrame it to the part's position and then parent it to it. end end end
Now my output:
Plant,
Axe (x13)
Why is this happening only with this for loop?
With this it works properly.
for i=1,10 do print(chooseRandomItem()) end
Now my output:
Knife,
Makeshift Spear,
Plant,
Knife,
Plant,
Angle Grinder (x2),
Makeshift Spear (x2),
Axe
Is there anyway to fix this, or I am simply doing something wrong?
Sorry if you're getting confused with this post, I'm not very good with explaining things and this is my first post, so bare with me.
Here's the whole script to help you all though
local Items = { {"Ikea Spell Book",1}, {"Baguette Sword",1}, {"Plant",10}, {"Axe",10}, {"Knife",10}, {"Makeshift Spear",10}, {"Angle Grinder",10}, } math.randomseed(tick()) local TotalWeight = 0 for _,ItemData in pairs(Items) do TotalWeight = TotalWeight + ItemData[2] end local function chooseRandomItem() local Chance = math.random(1,TotalWeight) local Counter = 0 for _,ItemData in pairs(Items) do Counter = Counter + ItemData[2] if Chance <= Counter then return ItemData[1] end end end for _,v in pairs(script.Parent:GetChildren()) do if v:IsA("BasePart") then if not v:FindFirstChildOfClass("Model") then local RandomItem = chooseRandomItem() local clone = game.ServerStorage.Pickups:FindFirstChild(RandomItem):Clone() clone:SetPrimaryPartCFrame(v.CFrame) clone.Parent = v -- Clone, CFrame it to the part's position and then parent it to it. end end end