I'm making a vote system and it should detect if there aren't any spectators in the game, if there isn't any, it's going to pick a random intvalue and add 13 to it. (There are 12 players maximum so just in case anything happens, 1 more is added) It then checks it who it is after.(That works fine)
This is what I have:
if #_G.spectators == 0 then status.Value = "There aren't any spectators in the game so it will be random." wait(5) status.Value = "Choosing Player." wait(3) for i, v in pairs(game:GetService('Teams'):FindFirstChild('Players'):GetPlayers()) do if v then local vValue = Instance.new("IntValue", replicatedStorage.Players) vValue.Name = v.Name vValue.Value = 0 end end for _, v in pairs(replicatedStorage.Players:GetChildren()) do local randomPl = replicatedStorage.Players:GetChildren()[math.random(1,#replicatedStorage.Players:GetChildren())] if randomPl == v.Name then if v:IsA("IntValue") then v.Value = 13 end end end status.Value = "Player Chosen." wait(2) else -- code here end
There are no errors in the output.
You're picking a random value in each iteration, rather than before the loop. Not only does this make it rather unlikely that even one will be chosen, it also has the rare, potential issue of picking more than one value. You can easily fix the problem by swapping lines 13 and 14, that is
local List = replicatedStorage.Players:GetChildren(); local randomPl = List[math.random(#List)]; for _, v in pairs(List) do if randomPl == v.Name then if v:IsA("IntValue") then v.Value = 13 end end end
Hope this helped. Read more about loops.
EDIT: Something I overlooked, on line 6 you have:
for i, v in pairs(game:GetService('Teams'):FindFirstChild('Players'):GetPlayers()) do
when I believe what you meant was
for i, v in pairs(game:GetService('Players'):GetPlayers()) do
EDIT, once again:
Apologies for all the edits, in a rush earlier I overlooked quite a lot. This snippet compared randomPl
, an IntValue
object to v.Name
, a string. This can be easily remedied by removing .Name
.
local List = replicatedStorage.Players:GetChildren(); local randomPl = List[math.random(#List)]; for _, v in pairs(List) do if randomPl == v then if v:IsA("IntValue") then v.Value = 13 end end end