I’m making a 2-player puzzle game, and i need a random player picker, but this script is not printing anything when i test it with one player.
I’m probably just being really stupid, but i don’t know what the problem is.
local players = game:GetService("Players")
local requiredAmount = 1
local playersInGame = players:GetPlayers()
repeat wait() until #playersInGame == requiredAmount
players.PlayerRemoving:Connect(function()
local remaining = players:FindFirstChildOfClass("Player")
if remaining then
remaining:Kick("Second player has left the game, thus making continuation impossible. That was super duper rude.")
end
end)
players.PlayerAdded:Wait()
local quietPlayer = playersInGame[math.random(1, #playersInGame)]
local quietCharacter = quietPlayer.Character or quietPlayer.CharacterAdded:Wait()
print("egeehehe")
playersInGame is a variable that is already a list of players during the time GetPlayers() got called (which is most likely zero in this case). You would have to run GetPlayers again to get the list in real time.
-- Services
local players = game:GetService("Players")
-- Amount of players in the game
local requiredAmount = 1
local playersInGame = players:GetPlayers()
-- flag to stop loop from checking if the right amount of players are in the game
local gameStarted = false
-- what to do when a player leaves
players.PlayerRemoving:Connect(function()
-- your code
local remaining = players:FindFirstChildOfClass("Player")
if remaining then
remaining:Kick("Second player has left the game, thus making continuation impossible. That was super duper rude.")
end
-- check if the game has ended because there aren't enough players
playersInGame = players:GetPlayers()
if #playersInGame < requiredAmount then
gameStarted = false
end
end)
-- every time a player adds, get all players so this can be used in the loop
players.PlayerAdded:Connect(function()
playersInGame = players:GetPlayers()
end)
-- how often to check if the right amount of players are in game
local timeout = 1
while wait(timeout) do
-- repeatedly check if the right amount of players are in game
if not gameStarted then -- this line is here to prevent your code from happening repeatedly
if #playersInGame == requiredAmount then
gameStarted = true
local quietPlayer = playersInGame[math.random(1, #playersInGame)]
local quietCharacter = quietPlayer.Character or quietPlayer.CharacterAdded:Wait()
print("egeehehe")
end
end
end
This uses events and keeps the script in a loop, will this method work?