I wanted to get a type of random player selector after a timer. After the timer is up, it sends a remoteEvent to change the player into a character.
But the issue is, is that when I do this method, RandomPlayer = Players[math.random(1, #Players)]
I saw on another forum (Probably outdated). It didn’t work! It keeps sending outputs like “Empty Value” or “Trying to get length of Instance Value”
I’ve tried to fix it to the best of my ability, but it just won’t work. The image below is my script. (Don’t judge it, I’m fairly of new to the studio.)
I have already tried to use #Players:GetChilderen() Unfortunately it does not work. Using the PlayerCount variable to get the number of players is possible. I have tried it before, but it gets the number of players and not the username of the players.
Alright, I figured it out with a little bit of help from Assistant.
All I need to do was create a table for the player names, and then use a for loop to get the players, and then use the local RandomPlayer = PlayerTable[math.random(1, #PlayerTable)] to get a random player.
I guess all I needed was a little bit of sleep and brainstorming!
This is the completed script!
local Timer = 120
local LobbyTimer = 10
local CanTime = true
local Players = game:GetService("Players")
local PlayerCount = 0
local PlayerTable = {}
game.Players.PlayerAdded:Connect(function(player)
table.insert(PlayerTable,player.Name)
print(table.concat(PlayerTable,", "))
end)
game.Players.PlayerRemoving:Connect(function(player)
local index = table.find(PlayerTable, player.Name)
if index then
table.remove(PlayerTable, index)
print(table.concat(PlayerTable, ", "))
end
end)
--Counts down the game timer.
function GameTimerCountDown()
while wait(1) do
game.ReplicatedStorage.Timer:FireAllClients(Timer)
Timer = Timer - 1
if Timer == 0 then
Timer = 120
LobbyTimerCountDown()
break
end
end
end
--Counts down the lobby timer.
function LobbyTimerCountDown()
while wait(1) do
print(#Players:GetPlayers())
if #Players:GetPlayers() >= 1 then
game.ReplicatedStorage.Timer:FireAllClients(LobbyTimer)
LobbyTimer = LobbyTimer - 1
if LobbyTimer == 0 then
for i, player in pairs(PlayerTable) do
local RandomPlayer = PlayerTable[math.random(1, #PlayerTable)] --BROKEN PART OF SCRIPT
print(RandomPlayer)
local TaggerPlayer = game.Players:FindFirstChild(RandomPlayer)
if player == RandomPlayer then
game.ReplicatedStorage.Tagger:FireClient(TaggerPlayer)
else
game.ReplicatedStorage.Runner:FireClient(player)
end
end
LobbyTimer = 30
GameTimerCountDown()
break
end
else
game.ReplicatedStorage.TimerFail:FireAllClients()
end
end
end
LobbyTimerCountDown()