Random parts of localscript nonfunctional after character death

Genuinely have no idea on this one. Trying to get a rig to constantly being running even after dead, CFrames and :ToPivot die randomly in the Runservice however the renderloop function is still running. Script is located in StarterPlayerScripts and is cut to the only relevant parts, no CharacterAdded() or any sort of PlayerAdded() in the script. Help!

local loop = nil

local mult = 3
local swayOffset = CFrame.new()
local lastCameraCF = workspace.CurrentCamera.CFrame

function renderloop() --bind this camera render loop
	local rotation = workspace.CurrentCamera.CFrame:toObjectSpace(lastCameraCF)
	local x,y,z = rotation:ToOrientation()
	swayOffset = swayOffset:Lerp(CFrame.Angles(math.sin(x)*mult,math.sin(y)*mult,0), 0.1)
	rig.PrimaryPart.CFrame = rig.PrimaryPart.CFrame * swayOffset 
	lastCameraCF = workspace.CurrentCamera.CFrame
end

if loop then
	loop:Disconnect()
end

loop = RunService.RenderStepped:Connect(function()
	local currentTime = tick()
	if Humanoid.MoveDirection.Magnitude > 0 then -- we are walking
		isWalking = true
		local bobbleX = math.cos(currentTime * 10) * .2
		local bobbleY = math.abs(math.sin(currentTime * 10)) * .2

		local bobble = Vector3.new(bobbleX, bobbleY, 0)

		Humanoid.CameraOffset = Humanoid.CameraOffset:Lerp(bobble, .25)
	else -- we are not walking
		isWalking = false
		Humanoid.CameraOffset = Humanoid.CameraOffset * .75	
	end
	
	if isWalking then
		x1 = x1 + 0.1
		x2 = x2 + 0.1		
		x3 = x3 + 0.1
		WalkingOffset = CFrame.new(
			math.sin(x2 * (WalkSpeed/OGWalkSpeed))/-15 , 
			math.sin(x1 * (WalkSpeed/OGWalkSpeed))/-15 ,
			math.sin(x3 * (WalkSpeed/OGWalkSpeed))/15) 
			* CFrame.Angles(0,0,0)
	else
		WalkingOffset = WalkingOffset:Lerp(CFrame.new(), 0.2)	
	end
	
	rig:PivotTo(CurrentCamera.CFrame * module.CameraOffset * WalkingOffset)
	renderloop()
	
end)

This is probably because you’re referencing the destroyed character instead of the new one. There are a few ways to approach this, I assume this is a localscript in starterplayerscripts?

If so, try something like this:

local players = game:GetService('Players')
local localPlayer = players.LocalPlayer
-- ...

localPlayer.CharacterAdded:Connect(function(character)
    humanoid = character:WaitForChild('Humanoid')
end)

loop = runService.RenderStepped:Connect(function()
    local currentTime = tick()
    if not humanoid then
        return
    end
    -- rest of your function as normal
1 Like

It ends up nil, its not grabbing the humanoid and CharacterAdded() is not working at all, any other ideas muchacho?