So, I'm making a randomizer type game where you get random items after every time you die, but the main issue is the the point of the game where you get random items. Everything works great, just except for when you respawn to get your items. When you respawn, the game will either crash, or give you 60+ items where you're meant to only get three. I've tried checking the amount of tools a player in the table has in their backpack, and so many other attempts that I just completely forgot about. And there aren't any errors in the output.
for x = 300,0,-1 do for j,plr in pairs(plrs) do if plr then if plr.Character then -- they in the game plr.Character.Humanoid.Died:Connect(function() wait(game.Players.RespawnTime) local weapons = game.ServerStorage:WaitForChild("weapons") local melee = weapons:WaitForChild("Melee"):GetChildren() local ranged = weapons:WaitForChild("Ranged"):GetChildren() local misc = weapons:WaitForChild("Misc"):GetChildren() local chosenMelee = melee[math.random(1,#melee)]:Clone() local chosenRanged = ranged[math.random(1,#ranged)]:Clone() local chosenMisc = misc[math.random(1,#misc)]:Clone() chosenMelee.Parent = plr.Backpack chosenRanged.Parent = plr.Backpack chosenMisc.Parent = plr.Backpack print(plr.Name,chosenMelee.Name,chosenRanged.Name,chosenMisc.Name) end) end else print(plrs[j].Name..' was removed') table.remove(plrs,j) end end wait(1) if x == 0 then --end of game wait(2) break end end
I see your problem, one solution that I have in mind is that you can make a folder(parented wherever is best for you) with tools(in your case, you would create 3 folders) and get it's children in the script.
Using the event of Player called CharacterAdded, you can do something like this(I'll be using only 1 folder)
local getTools = game:GetService('ReplicatedStorage').ToolsFolder:GetChildren() game:GetService('Players').PlayerAdded:Connect(function(plr) -- gets player from PlayerAdded local BP = plr.Backpack plr.CharacterAdded:Connect(function() -- events fires when character is added local clonedTool = getTools[math.random(1, #getTools)]:Clone() -- the selected tool is cloned clonedTool.Parent = BP end)