So, I need a little help with a death system. I have a script, that should change the camera to the partcam1 upon death of the character:
local player = game.Players.LocalPlayer
local camera = game.Workspace.CurrentCamera
local part = game.Workspace.partcam1
local sound = game.Workspace.jumscare
function onPlayerDied()
camera.CameraType = Enum.CameraType.Scriptable
camera.CFrame = part.CFrame
sound:Play()
wait(5)
camera.CameraType = Enum.CameraType.Custom
camera.CameraSubject = player.Character.Humanoid
end
player.Character.Humanoid.Died:Connect(onPlayerDied)
however this doesnt seem to work. I dont know much in scripting, so what do I fix here?
Developer Console doesnt help much, as it says there are no errors
local player = game:GetService("Players").LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
local camera = game.Workspace.CurrentCamera
local part = game.Workspace.partcam1
local function onPlayerDied()
camera.CameraType = Enum.CameraType.Scriptable
camera.CFrame = part.CFrame
task.wait(1)
camera.CameraType = Enum.CameraType.Custom
camera.CameraSubject = humanoid
end
humanoid.Died:Connect(onPlayerDied)
The scope is the difference. Local Functions can be used only in the scope they were created, while (global) functions can be used outside their scope.
A crude example to show it vividly
if humanoid.Health > 0 then
local function changeCamera(subject)
camera.CameraSubject = subject
end
changeCamera(deathCamera) --Will Work
task.wait(5)
changeCamera(player.Character.Humanoid) --Will work
end
changeCamera(deathCamera) --Will Error. The function doesn't exist here.
In the above example, the Local Function is created inside the “If” statement scope, so it can only be called inside that scope. If you try and call the function outside of that “If”, it’s gonna throw an error, because the function doesn’t exist outside that scope.
If you remove the “local” in the function above, you can call it anywhere in the script, including outside the “If” scope, and inside other scopes.
There are other minor things, like global function can be called before it is created, like before the line the actual function is written. But the main difference is still the scope.
It is recommended to always use Local for performance benefits, unless you Have To use global.