I want the game to check if all the NPCs or enemies within a folder are dead or removed from the world, and then teleport all players to a different place. I am not sure what is wrong with my code. The folder definitely does clear out but the script does not teleport the player.
local lobbyId = 11955772891 --Lobby's place id
game:GetService("Players").PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function(character)
workspace.NPCs.ChildRemoved:Connect(function()
if workspace.NPCs:GetChildren() == 0 then
game:GetService("TeleportService"):Teleport(lobbyId, player)
end)
end)
end)
workspace.NPCs.ChildRemoved:Connect(function()
if #workspace.NPCs:GetChildren() == 0 then
game:GetService("TeleportService"):Teleport(lobbyId, player)
end
end)
You just forgot the # in the GetChildren so it’s saying if {} == 0 which is false.
The # makes it compare the length of the list instead of the list.
Also not particularly a big deal, but your binding a new function for every player. It would be better from a code structure standpoint to just do that children check and then teleport all players inside that rather than using the playerAdded event to get the player variable. But technically both will work.
So more like this
game.WorkspaceNPCs.ChildRemoved:Connect(function()
if #game.Workspace.NPCs:GetChildren() == 0 then
for _, player in pairs(game.Players:GetPlayers()) do
-- teleport player here. Sorry for bad formatting, I’m on mobile and out of time.
end
end)
workspace.NPCs.ChildRemoved:Connect(function()
if #game.Workspace.NPCs:GetChildren() == 0 then
game:GetService("TeleportService"):TeleportAsync(lobbyId, game.Players:GetPlayers())
end
end)