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

How to get a random one player from get children?

I'm creating a sort of admin script, and I need this function to get only one player.

for i,v in pairs(game.Players:GetPlayers()) do
        if v.Name:sub(1, #find) == find then
            table.insert(players,v)
        end
end

Ignore the second line for the most part, basically I get all the players, and then if someone does something like ;kill b it would find a player's name starting with b, but if multiple people's names began with b it would get them all. How do I after the second line pick only one of all the players, and if it's only one then just do it on them?

1 answer

✓ Accepted answer

It's actually pretty simple. Use math.random(). Basically, math.random() returns a random number in between 2 given numbers. You know how you can refer to a certain member of a table by using tablename[number]? Well with this, you just use tablename[math.random(1, #tablename)]. I'll add the part where it'll kill a random player to your script below.

for i,v in pairs(game.Players:GetPlayers()) do
        if v.Name:sub(1, #find) == find then
            table.insert(players,v)
        end
end
--part I added below
local player = players[math.random(1, #players)]
if workspace:FindFirstChild(player.Name) then
	workspace:FindFirstChild(Player.Name).Humanoid:ChangeState(Enum.HumanoidStateType.Dead)
end

If it doesn't work, comment below and let me know if it returned any errors in the output.

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