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

How do I pick a random player?

I asked this recently and got an answer, but now I don't think it works as it should. What I want it to do is select a random player and sets a value inside 'Settings' to true. This is what I got but whenever I test it, it only picks the first person to join the server repeatedly

plrs = game.Players
		p = plrs:GetChildren()
        for i = 1,#p do
        b = math.random(1,i)
        p[b].Settings.Tagger.Value = true
end

1 comment

2

Plr = Plrs[random(1, #Plrs)]?

1 answer

You need to use the math.random and use plrs:GetPlayers() not plrs:GetChildren()

and for math.random use math.random(1,#p) and use local VARIABLE = ...

dont need to use for loop.

here is a examples of math.random:

-- 1 - Get random item from table.
local Table = {"Apple","Orange"} -- Items table.
local selected_value = math.random(1,#Table) -- Get random number with 1 to length of table.
local value = Table[selected_value] -- Get selected value
print("I got the value: " .. tostring(value)) -- Print the value.

-- 2 - Get random item from model, part...
local model = workspace.Model:GetChildren() -- For get length of model, part... you need to use :GetChildren(). for get of players use :GetPlayers()
local random_value = math.random(1,#model) -- Get random number with 1 to length of model objects.
local item = model[random_value] -- Get the value
print("I got the item: " .. tostring(item.Name)) -- Print the value

Here is fixed script:

local plrs = game:GetService("Players")
local p = plrs:GetPlayers()
local selected_value = math.random(1,#p)
p[selected_value].Settings.Tagger.Value = true

Wiki pages:

math.random

GetPlayers()

GetChildren()

Hope it helped :)

Errors? tell-me on comments.

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