Connections not firing when in a function

I’m trying to add connections whenever a character respawns, but none of the events fire.

I’ve tried different events, but none of them seem to work
If I put them outside the function they work, but they get reset when the character dies.

I couldn’t find any helpful posts here already, but if there is one that I somehow missed, please link it!

This is the code that’s having the problems, it’s a localscript.

local function onCharacterAdded()
	print("character has been added")
	character = player.Character
	characterHead = character:WaitForChild("Head")
	humanoid = character:WaitForChild("Humanoid")

	-- Connections
	character.ChildAdded:Connect(function(item)
		print("Test1")
		onChildAdded(item)
	end)
	character.ChildRemoved:Connect(function(item)
		print("Test2")
		onChildRemoved(item)
	end)
	humanoid.Died:Connect(function()
		print("aah")
		onHumanoidDeath()
	end)

	print(humanoid.Parent.Name)
	viewmodel.Parent = workspace
	runService:BindToRenderStep("CameraUpdate", Enum.RenderPriority.Camera.Value, function(deltaTime) -- Binds a cameraUpdate so the viewmodel constantly follows the camera
		local rotation = workspace.CurrentCamera.CFrame:toObjectSpace(lastCameraCF) --get cframe delta.
		local x,y,z = rotation:ToOrientation() --I'm sure there are better ways to get rotation but this will work for now.
		swayOffset = swayOffset:Lerp(CFrame.Angles(math.sin(x)*multiplier,math.sin(y)*multiplier,0), 0.1) --calculate the sway using SIN
		lastCameraCF = workspace.CurrentCamera.CFrame --update the last cframe

		viewmodelHead.CFrame = workspace.CurrentCamera.CFrame:Lerp(workspace.CurrentCamera.CFrame, aimValue) * swayOffset
	end)
end

onCharacterAdded()

player.CharacterAdded:Connect(onCharacterAdded)

If you need any additional information feel free to ask :slight_smile:

What parent is this script under? Try out putting the script under StarterCharacterScript and see if that helps fire those events

2 Likes

I changed the scripts parent to StarterCharacterScript and all works well now, thank you so much!

1 Like

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