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

Help with code that chooses a player at random when there are at least 2 players in the game?

I used variable plrs >= 2 and the script won't run.

dft = {} 
local plrs = #game:GetService('Players'):GetChildren()
function GetPlayers()
local c = game.Players:GetChildren() 
for i = 1, #c do 
table.insert(dft, c[i].Name) 
end 
end
if plrs >= 1 then

function Randomize()
GetPlayers()
local d = math.random(1, #dft) 
local s = d 
local m = Instance.new("Message", game.Workspace) 
m.Text = "The random player is ... "..dft[s].."!" 
wait(2) 
m:Remove()
local rndm = game.Players:FindFirstChild(dft[s])
if (rndm ~= nil) then 
local Player = rndm.Character
Player:MoveTo(Vector3.new(6, 13, 49))
end
end

while true do
wait(5)
Randomize()
end

2 answers

✓ Accepted answer

Indenting is very, very important. Makes it really easy to spot your if statement that was out of place

dft = {} 
local plrs = #game:GetService('Players'):GetChildren()

function GetPlayers()
	local c = game.Players:GetChildren() 
	for i = 1, #c do 
	    table.insert(dft, c[i].Name) 
	end 
end

--if plrs >= 1 then -- This shouldn't be here

function Randomize()
	GetPlayers()
	local d = math.random(1, #dft) 
	local s = d 
	local m = Instance.new("Message", game.Workspace) 
	m.Text = "The random player is ... "..dft[s].."!" 
	wait(2) 
	m:Remove()
	local rndm = game.Players:FindFirstChild(dft[s])
	if (rndm ~= nil) then 
		local Player = rndm.Character
		Player:MoveTo(Vector3.new(6, 13, 49))
	end
end

while wait(5) do	
	print("Done waiting.")
	if plrs >= 1 then -- If statement goes here
		print("Randomizing.")
		Randomize()
	else
		print("Not enough players.")
	end
	-- Reassign variable with the new current amount of players
	plrs = #game:GetService('Players'):GetChildren()
end

2 comments

0

Is there any way I can stop the script from repeating? Thanks.

0

You remove the while loop or set the while condition to something like while wait(5) and not ranOnce do then inside the while loop you set ranOnce to true.

Pretty easy, you get the children of players and get a random value out of the table like this

while wait() do
	local plrs = #game.Players:GetPlayers()
	if plrs >= 2 then
		local randomPlayer = game.Players:GetPlayers()[math.random(1, plrs)]
	end
end

You would add a sort of debounce to the script though.

(I didn't fix your script because this code would probably be way better)

But the problem to your script is most likely because you don't put the #players in the loop wich means it will only get it once, at the start of the script.

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