Help on Spectate Script

Hey, I created a spectate function which works fine. The issue is when I want it to re-spectate after the (who you were) spectating died.

Thanks for any help in advance!
(repost as my previous one was sent to the shadow realm)

Here’s the script:

workspace.ChildAdded:Connect(function(char)
	local plr = char
	if game.Players:FindFirstChild(plr.Name) ~= nil then
		if plr.Name:lower() == tostring(spec):lower() then
			spectatezON(plr.Name)
		end
    end
end)

SPECTATE FUNCTION

local function spectatezON(player)
	game.workspace.CurrentCamera.CameraSubject = game.Players:FindFirstChild(tostring(player)).Character:WaitForChild("Humanoid")
	game.workspace.CurrentCamera.CameraType = "Custom"
	game.workspace.CurrentCamera.CFrame = game.Players:FindFirstChild(tostring(player)).Character:WaitForChild("Head").CFrame
end

Make a variable to store the current connection for what we’ll do.When you’re spectating, make a CharacterAdded event on the player you’re spectating so when they respawn again, it’ll update the CameraSubject accordingly. I also recommend guard clauses and variables since you’re repeating a bit. In the end, something like this

Area of code relating to your spectatezON function

local currentcam = workspace.CurrentCamera

local connection

local function spectatezON(player)
	local player = game:GetService("Players"):FindFirstChild(tostring(player))
	if not player then return end
	local char = player.Character
	if not char then return end
	currentcam.CameraSubject = char:WaitForChild("Humanoid")
	currentcam.CameraType = "Custom"
	currentcam.CFrame = char:WaitForChild("Head").CFrame
	if connection then connection:Disconnect() end
	connection = player.CharacterAdded:Connect(function(newChar)
		currentcam.CameraSubject = newChar:WaitForChild("Humanoid")
		currentcam.CFrame = char:WaitForChild("Head").CFrame
	end)
end
2 Likes

Wow works perfectly, thank you very much!!
I’ll be sure to repeat less, I’ve actually been working on that recently, so hopefully my future scripts will be a lot more organized and repetitive lol.
Thanks once again!

1 Like

Anytime! If you have anymore issues don’t be afraid to make another post!

And that’s good you’re repeating less! Repetition is one of the things I like to point as it be beneficial to fix!

1 Like