Map script fails if character dies right before loop starts

I am trying to have a script that has a loop of rotating maps. But whenever somebody dies right before the loop, the script breaks.

local players = game:GetService("Players")
local replicated = game:GetService("ServerStorage")
local lobbyMap = replicated.LobbyMap
local mapsFolder = replicated.Maps
local maps = mapsFolder:GetChildren()


while true do
	local lobbyClone = lobbyMap:Clone()
	lobbyClone.Parent = workspace
	wait(5)
	game.ReplicatedStorage.DisableInventory:FireAllClients()
	for _, player in ipairs(players:GetPlayers()) do
		local character = player.Character or player.CharacterAdded:Wait()
		local humanoid = character.Humanoid
		humanoid:UnequipTools()
		character.Torso.CFrame = workspace.LobbyMap.SpawnLocation.CFrame
	end

	local hint1 = Instance.new("Hint")
	hint1.Parent = workspace
	for i = 30, 0, -1 do
		hint1.Text = ("Game will start in: "..i)
		task.wait(1)
	end
	hint1:Destroy()

	local randomMap = maps[math.random(#maps)]:Clone()

	local message1 = Instance.new("Message")
	message1.Parent = workspace
	message1.Text = "The next map will be... "..randomMap.Name.."!"

	task.wait(2)
	message1:Destroy()
	randomMap.Name = "Map"
	randomMap.Parent = workspace
	
	wait(3)
	for _, player in ipairs(players:GetPlayers()) do
		local character = player.Character or player.CharacterAdded:Wait()
		character.Torso.CFrame = workspace.Map.SpawnLocation.CFrame
	end
	game.ReplicatedStorage.DisableInventory:FireAllClients()

	local lobby = workspace:FindFirstChild("LobbyMap")
	if lobby then
		lobby:Destroy()
	end

	local hint2 = Instance.new("Hint")
	hint2.Parent = workspace
	for i = 300, 0, -1 do
		hint2.Text = ("Game will end in: "..i)
		task.wait(1)
	end
	hint2:Destroy()

	local currentMap = workspace:FindFirstChild("Map")
	if currentMap then
		currentMap:Destroy()
	end
end
1 Like

Try to check if the player’s are alive before teleporting them

how would I do that? (30 stuff)

check the health of the humanoid

Check humanoid health here

for _, player in ipairs(players:GetPlayers()) do
	local character = player.Character or player.CharacterAdded:Wait()
	local humanoid = character.Humanoid
	humanoid:UnequipTools()
	character.Torso.CFrame = workspace.LobbyMap.SpawnLocation.CFrame
end

and here

for _, player in ipairs(players:GetPlayers()) do
	local character = player.Character or player.CharacterAdded:Wait()
	character.Torso.CFrame = workspace.Map.SpawnLocation.CFrame
end

thought it worked for a while but the problem in the console said that it couldn’t find the Torso of player.

I am surprised to say that, it never worked. I was just getting lucky whenever nobody died before the loop.