Weird problems with my ragdoll script

I want to fix my script which put the player in ragdoll temporarly

The first time the npc or player gets put on ragdoll it works fine but then the limbs start jumping around weirdly.

Putting the player in ragdoll

script.Folder.ChildAdded:Connect(function()
	local PlayerParts = Character:GetDescendants()		
	for i,M6D in pairs(PlayerParts) do
		if M6D:IsA("Motor6D") then
			if M6D.Name ~= "Root" then
				if not M6D.Parent:FindFirstChildWhichIsA(SocketType) then
					local Socket = Instance.new(SocketType)
					M6D.Parent = M6D.Part1
					Socket.LimitsEnabled = true
					Socket.Radius = .25
					Socket.TwistLimitsEnabled = false
					Socket.TwistLowerAngle = 360
					Socket.TwistUpperAngle = -180
					Socket.UpperAngle = 90
					local M0,M1
					if not M6D.Part0:FindFirstChild(M6D.Name .. "RigAttachment") then
						print("A")
						M0 = Instance.new("Attachment")
						M0.Name = M6D.Name .. "RigAttachment"
						M0.Parent = M6D.Part0
						M0.CFrame = M6D.C0
						print(M0.Name .. "A0")
					end
					if not M6D.Part1:FindFirstChild(M6D.Name .. "RigAttachment") then
						M1 = Instance.new("Attachment")
						M1.Name = M6D.Name .. "RigAttachment"
						M1.Parent = M6D.Part1
						M1.CFrame = M6D.C1
						print(M1.Name .. "A1")
					end

					Socket.Parent = M6D.Parent	
					Socket.Attachment0 = M6D.Part0:FindFirstChild(M6D.Name .. "RigAttachment")
					Socket.Attachment1 = M6D.Part1:FindFirstChild(M6D.Name .. "RigAttachment")
					game.Workspace.CurrentCamera.CameraSubject = Character.Head
					M6D.Enabled = false
					Hm:ChangeState(Enum.HumanoidStateType.Physics)
					Ragdolling = true
					HmHRP.CanCollide = false
				

							end
			end
		end
	end

end)

Putting the player off ragdoll

script.Folder.ChildRemoved:Connect(function()
	local PlayerParts = Character:GetDescendants()	
	if Ragdolling == true then
		for i,M6DBSC in pairs(PlayerParts) do
			if M6DBSC:IsA(SocketType) then
				M6DBSC:Destroy()
			elseif M6DBSC:IsA("Motor6D") then
				M6DBSC.Enabled = true
			end
		end
		
		HmHRP.CFrame = HmHRP.CFrame + Vector3.new(0,2,0)
		HmHRP.CanCollide = true
		game.Workspace.CurrentCamera.CameraSubject = Character.Humanoid
		Hm:ChangeState(Enum.HumanoidStateType.GettingUp)
	end

end)