So i have a game script that picks a random player and then runs code into that player. After a certain amount a time, that loop would end and a new player is picked. The problem is tho, when the player leaves it would obviously break the script and i don't know how to get it to stop and reset after the player leaves. –
Here is some example code for what i'm using.
while true do wait(0.5) local plr = game.Players:GetChildren() if #plr > 1 then local Pick = plr[math.random(1, #plr)] if Pick.Character then local char = Pick.Character --Code and stuff end else --Makes a Gui message saying at least two players are needed end end
There are a few options. I usually fill an array with the current players and remove them if certain things happen. For instance, you could remove them from your array when they leave or die. You can check if that person has been chosen before you do that though, so you could then assign someone new.
local playing = {} local function returnPlayerInTable(PlayerInQuestion) for i,v in pairs(playing) do if v.player.Name == PlayerInQuestion.Name then -- return index (incase we need to remove them) and their table in playing. return i,v end end return false end local function addPlayer(newPlayer, isChosen) local entry = {} -- fill table what what you want to keep track of. entry.player = newPlayer entry.chosen = isChosen table.insert(playing, entry) -- playing will now look something like this -- playing = { {player = player1, chosen = true} } end game.Players.PlayerRemoving:connect(function(playerLeft) local posInTable, PlayerTable = returnPlayerInTable(playerLeft) if posInTable then if PlayerTable.player.Name == playerLeft.Name -- pick new person and change chosen to true end -- Remove them from table because they left table.remove(playing, posInTable) end end while true do if game.Players.NumPlayers > 1 then local currentPlayers = game:GetService("Players"):GetPlayers() local pick = currentPlayers[math.random(#currentPlayers)] -- you should probably have some backup or more secure methods -- for pick incase it doesn't pan out for some reason. -- You can use CurrentPlayers or get an updated array, like below. for i,v in pairs(game.Players:GetPlayers()) do if v.Name == pick.Name then -- Add player to playing, make them the chosen one addPlayer(v, true) else -- Add player to playing, don't make them the chosen one addPlayer(v, false) end end end wait(.05) end
try something like this:
game.Players.PlayerRemoving:connect(function() break end)
that would be somewhere in your loop
lmk if it works