I am trying to make a spectate system where when a player presses a the Shift button when he/she is dead, it will focus the camera on a player that is alive. When a player is dead in my game, his/her character is set to nil. The player's character doesn't reload until the next round.
--[[
NOTE: This is in a LocalScript in StarterPack.
It makes sure if the player does not have a Character to continue.
]]--
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local cam = game.Workspace.CurrentCamera
mouse.KeyDown:connect(function(key)
if key:byte() == 48 then --If left shift is pressed
if not player.Character then --If the player is dead
local randomPlayer = nil
for i, v in pairs (game.Players:GetPlayers()) do
if player:FindFirstChild("Character") then
randomPlayer = v --Finds a random player
print("Spectating: "..randomPlayer.Name)
cam.CameraType = Enum.CameraType.Follow
cam.CameraSubject = randomPlayer.Character.Humanoid
break
end
end
end
end
end)
It prints the name of the person whom you are supposed to spectate in the output, but after that, I get an error saying attempting to index a nil value for the line where I am setting the CameraSubject to the randomPlayer's humanoid. I have tried to set the CameraSubject to randomPlayer's head as well, but it gave me the same error message.
Any suggestions on how I can change the CameraSubject of a player's camera when his/her character is in a nil state?

1 comment
Oh, okay. Thanks. That "player" in line 15 was just a mistake of transferring. I didn't want to copy and paste my exact code, so I changed it up a bit. It's not like that in the real thing.