Spectating gui breaking when player dies

Hey everyone! So today, my friend encountered a error in a script he made, he doesn’t know how to fix it because when a person dies while your spectating them, the camera breaks, and doesn’t follow the person anymore. I looked at the code and wasn’t too sure of how to fix it, so I came to the devfourm. Here is the script my friend made.

local players = nil
local number = 1
local maxnumber = 0
local player = game.Players.LocalPlayer

script.Parent.Next.MouseButton1Click:connect(function(right)
	players = game.Players:GetChildren()
	number = number + 1
	if players[number] ~= nil then
		game.Workspace.CurrentCamera.CameraSubject = players[number].Character.Humanoid
		if players[number].Name ~= player.Name then
			script.Parent.PlayerName.Text = players[number].Name
		else 
			script.Parent.PlayerName.Text = "You"
		end
	elseif players[number] == nil then
		number = 1
		game.Workspace.CurrentCamera.CameraSubject = players[number].Character.Humanoid
		if players[number].Name ~= player.Name then
			script.Parent.PlayerName.Text = players[number].Name
		else 
			script.Parent.PlayerName.Text = "You"
		end
	end
end)

script.Parent.Previous.MouseButton1Click:connect(function(left)
	players = game.Players:GetChildren()
	maxnumber = #players
	number = number - 1
	if players[number] ~= nil then
		game.Workspace.CurrentCamera.CameraSubject = players[number].Character.Humanoid
		if players[number].Name ~= player.Name then
			script.Parent.PlayerName.Text = players[number].Name
		else 
			script.Parent.PlayerName.Text = "You"
		end
	elseif players[number] == nil then
		number = maxnumber
		game.Workspace.CurrentCamera.CameraSubject = players[number].Character.Humanoid
		if players[number].Name ~= player.Name then
			script.Parent.PlayerName.Text = players[number].Name
		else 
			script.Parent.PlayerName.Text = "You"
		end
	end
end)

script.Parent.Parent.Spectate.MouseButton1Down:connect(function(click)
	if script.Parent.Parent.Active.Value == false then
		script.Parent.Parent.Active.Value = true
		script.Parent.Parent.ChangePlayer.Visible = true
	elseif script.Parent.Parent.Active.Value == true then
		script.Parent.Parent.Active.Value = false
		script.Parent.Parent.ChangePlayer.Visible = false
		script.Parent.PlayerName.Text = "You"
		number = 1
		game.Workspace.CurrentCamera.CameraSubject = game.Players.LocalPlayer.Character.Humanoid

	end
end)
1 Like

I didn’t read the script you sent, but I read the issue. What about when you start spectating a player, store him in a variable and make a Humanoid.Died connection on his character, when that happens, wait until he gets a new character and wait for his HRP (or whatever you are following).