It still is saying the interval after random is empty even though I put #Players in it.
local playerService = game:GetService("Players")
local Players = playerService:GetPlayers()
local RandomPlayer = Players[math.random(#Players)]
It is still saying the interval after random is empty even though it is not.
I assume you’re running this on the server. You get that error, when your code is prematurely running before the player joins. I would add an if statement
to see if #Players > 0
, before the condition is met.
You are still miscomprehending what I meant, here’s the implicated script.
local Players = game:GetService("Players")
local playersReady = {}
local function pickRandomPlayer()
return playersReady[math.random(#playersReady)]
end
Players.PlayerAdded:Connect(function(player)
player.CharacterAdded:Wait() -- this was flawed, as it infinitely added up for each respawn
table.insert(playersReady, player)
end)
Players.PlayerRemoving:Connect(function(player)
local index = table.find(playersReady, player)
if index then
table.remove(playersReady, index)
end
end)
This fully works in my test game:
local playerService = game:GetService("Players")
local players = {}
playerService.PlayerAdded:Connect(function(player)
player.CharacterAdded:Wait()
table.insert(players, player)
-- Check if player was added to table
--[[
if table.find(players, player) then
print("Player Added Successfully!")
else
print("Player Not Added Successfully...")
end
]]
end)
playerService.PlayerRemoving:Connect(function(player)
local PlrToRemove = table.find(players, player)
if PlrToRemove then
table.remove(players, PlrToRemove)
end
end)
local function randomizePlayer()
local RandomNumber = math.random(1, #players)
for i, player in ipairs(game.Players:GetPlayers()) do
if i == RandomNumber then
player.Character.Head.Transparency = 1
end
end
end
-- DON'T CALL THIS IMMEDIATELY!!!
-- vvvv
randomizePlayer()
Here’s a model if you want: PlayerRandomizerScript - Roblox
Hope this helps!
Ok so I needed to access this table from multiple scripts so I used a module script and it works until the random part comes in. I put this:
if #playerReady >= 1 then
print(RandomPlayer)
end
RandomPlayer is equal to pickRandomPlayer(). and for some reason instead of print henberrysodapop it prints nil.
RandomPlayer
does not change by itself. You have to make sure to overwrite it whenever you’re absolutely sure that at least one player exists.
try print(RandomPlayer.Name) instead of just RandomPlayer