Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

My script is having trouble choosing 2 random players?

This is the part in my dueling game where it chooses 2 random players to fight. The problem is, I'm getting the error "ServerScriptService.MainScript:28: attempt to get length of local 'v' (a userdata value)". Any help?

for _, v in pairs(game.Players:GetPlayers()) do
		if v then
			local dueler1 = v[math.random(1, #v)]
			repeat local dueler2 = v[math.random(1, #v)] until dueler2 ~= dueler1

			table.insert(_G.duelers, dueler1.Name)
			table.insert(_G.duelers, dueler2.Name)

			status.Value = "The 2 duelers are " .. dueler1.Name .. " and " .. dueler2.Name
			wait(3)

			status.Value = "Now teleporting players to the map"
			wait(3)
			
			local torso1 = dueler1.Character:WaitForChild("Torso")
			local torso2 = dueler2.Character:WaitForChild("Torso")
			
			torso1.CFrame = CFrame.new(spawn1.Positon + Vector3.new(0, 2, 0))
			torso2.CFrame = CFrame.new(spawn2.Positon + Vector3.new(0, 2, 0))
			
			local sword1 = sword:Clone()
			sword1.Parent = dueler1.Backpack
			
			local sword2 = sword:Clone()
			sword2.Parent = dueler2.Backpack
			
			dueler1.Character.Humanoid.WalkSpeed = 0
			dueler2.Character.Humanoid.WalkSpeed = 0
		end
	end

1 answer

✓ Accepted answer

To get one random player, This one simple line of code does the trick.

game.Players:GetChildren()[math.random(#game.Players:GetChildren())]

Basically it uses math.random to generate one random output (a player) from the table input you provided (GetChildren)

This discussion is preserved as it was. New answers, comments, and votes are closed.