Ragdoll script acting strangely

I’m trying to make a ragdoll script that ragdolls your character when the humanoid’s health is 5 or lower, and then unragdolls it when it goes over 30. I’m having trouble with making it ragdoll in the first place, as when the health goes to 5 or under, this happens:

This is the script I’m using:

game.Players.PlayerAdded:Connect(function(p)
	p.CharacterAdded:Connect(function(c)
		c.Humanoid.BreakJointsOnDeath = false
		
		c.Humanoid.HealthChanged:Connect(function()
			if c.Humanoid.Health <= 5 then
				c.Humanoid:ChangeState(Enum.HumanoidStateType.Dead)
				c:WaitForChild("IsRagdolled").Value = true
				
				for _, v in pairs(c:GetDescendants()) do
					if v:IsA("Motor6D") then
						local a0, a1 = Instance.new("Attachment"), Instance.new("Attachment")
						a0.CFrame = v.C0
						a1.CFrame = v.C1
						a0.Parent = v.Part0
						a1.Parent = v.Part1
						
						local b = Instance.new("BallSocketConstraint")
						b.Attachment0 = a0
						b.Attachment1 = a1
						b.Parent = v.Part0
						
						local p1Value = Instance.new("ObjectValue")
						local p0Value = Instance.new("ObjectValue")
						p1Value.Name = "Part1Val"
						p0Value.Name = "Part0Val"
						p1Value.Parent = v
						p0Value.Parent = v
						p1Value.Value = v.Part1
						p0Value.Value = v.Part0
						
						v.Part1 = nil
						v.Part0 = nil
					end
				end
				
				c.HumanoidRootPart.CanCollide = true
			end
			
			if c.IsRagdolled.Value == true then
				if c.Humanoid.Health >= 30 then
					c.IsRagdolled.Value = false
					
					for i, v in pairs(c:GetDescendants()) do
						if v:IsA("Motor6D") then
							v.Part1 = v.Part1Val.Value
							v.Part0 = v.Part0Val.Value
							
							v.Part1Val:Destroy()
							v.Part0Val:Destroy()
						end
						
						if v:IsA("BallSocketConstraint") then
							v.Attachment0:Destroy()
							v.Attachment1:Destroy()
							
							v:Destroy()
						end
					end
				end
			end
		end)
	end)
end)

Any help is greatly appreicated.