CurrentCamera Does Not Go To a Part's CFrame

What I Want To Achieve
I am trying to make the player’s CurrentCamera go to a part called WorkCam, inside a folder called Cams, in the Workspace.

What the Issue Is
The code just doesn’t work. The error message says “Attempt to index nil with ‘CFrame’”.

The code is in StarterPlayerScripts and is written as follows:

local plr = game.Players.LocalPlayer
local plrcam = workspace.CurrentCamera

local cams = game.Workspace.Cams
local cam = cams:FindFirstChild("WorkCam")
local camPos = cam.CFrame

plr.CharacterAdded:Connect(function()
	plrcam.CFrame = camPos
end)

Other Solutions I’ve Tried
Doing some research, I’ve found tutorials on how to make cameras, but they all set the Current Camera to a CFrame, which somehow works for them without issue, or they use CFrame.lookAt, which would be inefficient.

Does anyone know what is wrong with my script?

I’m assuming this is the line where the code errors. Are you sure there’s a BasePart named WorkCam inside the Cam folder? If yes, maybe the issue is that it hasn’t loaded yet, so you can try :WaitForChild instead of :FindFirstChild which doesn’t really make sense since you’re sure the BasePart will be there.

local cam = cams:WaitForChild("WorkCam")

Also, changing the camera’s CFrame isn’t enough, you also need to change its CameraType to Scriptable.

plr.CharacterAdded:Connect(function()
	plrcam.CameraType = Enum.CameraType.Scriptable
	plrcam.CFrame = cam.CFrame
end)

Nothing is wrong with your script. It looks like you don’t understand how to properly write your variables. Using find first child before a part exists is a mistake. You need to learn how it works. There are other parts of your script also not written correctly. I will fix for you.

local plr = game.Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait() --Wait for character to exist
local plrcam = workspace.CurrentCamera
task.wait(1) --Wait for our variables to exist
local cams = game.Workspace:WaitForChild("Cams")
local cam = cams:WaitForChild("WorkCam")
local camPos = cam.CFrame
task.wait(1) --Wait for our parts to exist
if plr and char then --Check for the character and player existing
plrcam.CFrame = camPos --Set the cam CFrame to the parts CFrame once it exists
end

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.