Lock on breaks if a player dies

Hello! I have an issue with this code that I wrote that is shown below. Basically, it’s a script that allows your camera to lock onto the nearest player. For whatever reason, whenever a player dies (even if its not the player your locked onto), the lock on breaks until the player has respawned, then it relocks onto the nearest player.

Incase you were wondering, it is not aimbot, it’s for a turret I’m making.

game:GetService("RunService").RenderStepped:Connect(function()
	pcall(function()
		local players = game.Players
		local player = game.Players.LocalPlayer
		local distances = {}

		for i, v in pairs(players:GetPlayers()) do
			if v.Team == player.Team then
				if v.Team ~= nil then
					continue
				end
			end

			if v.Name == player.Name then
				continue
			end
			
			local character = v.Character
			local humanoid_root_part = character.HumanoidRootPart

			table.insert(distances, (humanoid_root_part.Position - player.Character.HumanoidRootPart.Position).Magnitude)

			if i == #players:GetChildren() then
				local min = math.min(table.unpack(distances))
				local index = table.find(distances, min)
				index += 1

				local closest_character = players:GetChildren()[index].Character
				game.Workspace.CurrentCamera.CFrame = CFrame.new(game.Workspace.CurrentCamera.CFrame.Position, closest_character.HumanoidRootPart.Position)
			end
		end			
	end)
end)

Probably because you’re doing

players:GetChildren()[index].Character 

to get the character, because character in that case can be non existant until it respawns, you should do a check to see if the character is loaded