Ragdoll uses global variable

I have a ragdoll code, but it uses a global variable for a player instead of a table. Thsi means sometimes ragdoll doesnt work and sometimes it teleports players to others.

I tried to use a table, but it ragdolls every player in the game when it’s supposed to only ragdoll one.

Can anyone help?

local ragdoll = nil
local char

local collision_part = Instance.new("Part")
collision_part.Name = "CP"
collision_part.TopSurface = Enum.SurfaceType.Smooth
collision_part.BottomSurface = Enum.SurfaceType.Smooth
collision_part.Size = Vector3.new(1, 1.5, 1)
collision_part.Transparency = 1

local AttactmentData = {
	["RA"] = {"Right Arm", CFrame.new(0, 0.5, 0), CFrame.new(1.5, 0.5, 0)},
	["LA"] = {"Left Arm", CFrame.new(0, 0.5, 0), CFrame.new(-1.5, 0.5, 0)},
	["RL"] = {"Right Leg", CFrame.new(0, 0.5, 0), CFrame.new(0.5, -1.5, 0)},
	["LL"] = {"Left Leg", CFrame.new(0, 0.5, 0), CFrame.new(-0.5, -1.5, 0)},
}

local function CreateJoint(j_type, p0, p1, c0, c1)
	local nj = Instance.new(j_type)
	nj.Part0 = p0
	nj.Part1 = p1
	if c0 then nj.C0 = c0 end
	if c1 then nj.C1 = c1 end
	nj.Parent = p0
end

local function SetupRagdollModel(ragdollModel, force)
	-- Clean up unnecessary parts from ragdoll clone
	local function scan(ch)
		for i = 1, #ch do
			scan(ch[i]:GetChildren())
			local obj = ch[i]
			if (obj:IsA("ForceField") or obj.Name == "HumanoidRootPart") or
				((obj:IsA("Weld") or obj:IsA("Motor6D")) and obj.Name ~= "HeadWeld" and obj.Name ~= "AttachementWeld") then
				obj:Destroy()
			end
		end
	end
	scan(ragdollModel:GetChildren())

	local function scanc(ch)
		for _, obj in pairs(ch:GetChildren()) do
			scanc(obj)
			if obj:IsA("Script") or obj:IsA("LocalScript") or
				((obj:IsA("Weld") or obj:IsA("Motor6D")) and obj.Name ~= "AttachementWeld") or
				obj:IsA("ForceField") or
				obj:IsA("ParticleEmitter") then
				obj:Destroy()
			elseif obj:IsA("BasePart") then
				obj.Velocity = Vector3.new(0, 0, 0)
				obj.RotVelocity = Vector3.new(0, 0, 0)
				if obj.Parent:IsA("Accessory") then
					obj.CanCollide = false
				end
			end
		end
	end
	scanc(ragdollModel)

	local fhum = ragdollModel:FindFirstChild("Humanoid")
	if fhum then
		fhum.HealthDisplayType = Enum.HumanoidHealthDisplayType.AlwaysOff
		fhum.PlatformStand = true
		fhum.DisplayDistanceType = Enum.HumanoidDisplayDistanceType.None
		fhum.Name = "RagdollHumanoid"
		fhum.MaxHealth = 100
		fhum.Health = fhum.MaxHealth
	end

	local Torso = ragdollModel:FindFirstChild("Torso")
	if Torso then
		local bv = Instance.new("BodyVelocity")
		bv.MaxForce = Vector3.new(1e9, 1e9, 1e9)
		bv.Velocity = force
		bv.Parent = Torso
		game.Debris:AddItem(bv, 0.06)
		local Head = ragdollModel:FindFirstChild("Head")
		if Head then
			CreateJoint("Weld", Torso, Head, CFrame.new(0, 1.5, 0))
		end

		for att_tag, att_data in pairs(AttactmentData) do
			local limb = ragdollModel:FindFirstChild(att_data[1])
			if limb then
				local att1 = Instance.new("Attachment")
				att1.Name = att_tag
				att1.CFrame = att_data[2]
				att1.Parent = limb

				local att2 = Instance.new("Attachment")
				att2.Name = att_tag
				att2.CFrame = att_data[3]
				att2.Parent = Torso

				local socket = Instance.new("BallSocketConstraint")
				socket.Name = att_tag .. "_SOCKET"
				socket.Attachment0 = att2
				socket.Attachment1 = att1
				socket.Radius = 0
				socket.Parent = Torso

				limb.CanCollide = false

				local cp = collision_part:Clone()
				local cp_weld = Instance.new("Weld")
				cp_weld.C0 = CFrame.new(0, -0.25, 0)
				cp_weld.Part0 = limb
				cp_weld.Part1 = cp
				cp_weld.Parent = cp
				cp.Parent = ragdollModel
			end
		end
	end
end

function EnableRagdoll(player, force)
	if ragdoll then return end -- already ragdolled, ignore

	char = player.Character
	if not char then return end
	char.Archivable = true

	-- Convert 'force' to Vector3 direction if needed
	if typeof(force) == "number" then
		local hrp = char:FindFirstChild("HumanoidRootPart")
		if hrp then
			force = hrp.CFrame.LookVector * force
		else
			force = Vector3.new(0, force, 0) -- fallback up force
		end
	elseif typeof(force) ~= "Vector3" then
		force = Vector3.new(0, 0, 0)
	end

	-- Clone the character for ragdoll
	ragdoll = char:Clone()
	ragdoll.Name = char.Name .. "_Ragdoll"
	SetupRagdollModel(ragdoll, force)
	ragdoll.Parent = workspace

	local bv = Instance.new("BodyVelocity")
	bv.MaxForce = Vector3.new(1e9, 1e9, 1e9)
	bv.Velocity = force
	bv.Parent = char.HumanoidRootPart
	game.Debris:AddItem(bv, 0.06)

	-- Hide original character parts (don’t destroy!)
	for _, part in pairs(char:GetChildren()) do
		if part:IsA("BasePart") and part.Name ~= "HumanoidRootPart" then
			part.Transparency = 1
			part.CanCollide = false
		elseif part:IsA("Accessory") then
			if part:FindFirstChild("Handle") then
				part.Handle.Transparency = 1
				part.Handle.CanCollide = false
			end
		end
	end

	-- Freeze original humanoid controls
	char.Humanoid.PlatformStand = true
end

function DisableRagdoll(player)
	if not ragdoll then return end
	
	local ragdollCF
	
	if ragdoll:FindFirstChild("Torso") then
		ragdollCF = ragdoll.Torso.CFrame
	end

	-- Remove ragdoll model
	ragdoll:Destroy()
	ragdoll = nil

	char = player.Character
	if not char then return end
	
	if ragdollCF and char:FindFirstChild("HumanoidRootPart") then
		player.Character.HumanoidRootPart.CFrame = ragdollCF
	end

	-- Show original character parts back
	for _, part in pairs(char:GetChildren()) do
		if part:IsA("BasePart") and part.Name ~= "HumanoidRootPart" then
			part.Transparency = 0
			part.CanCollide = true
			game.PhysicsService:SetPartCollisionGroup(part, "Players")
		elseif part:IsA("Accessory") then
			if part:FindFirstChild("Handle") then
				part.Handle.Transparency = 0
				part.Handle.CanCollide = true
			end
		end
	end

	-- Unfreeze controls
	char.Humanoid.PlatformStand = false
end

game.ReplicatedStorage.Events.ToggleRagdoll.Event:Connect(function(player, toggle, force, attacker)
	if toggle then
		-- Ensure force is a Vector3 direction
		if typeof(force) == "number" then
			local hrp = attacker.HumanoidRootPart or player.Character.HumanoidRootPart
			if hrp then
				force = hrp.CFrame.LookVector * force
			else
				force = Vector3.new(0, force, 0)
			end
		elseif typeof(force) ~= "Vector3" then
			force = Vector3.new(0, 0, 0)
		end
		EnableRagdoll(player, force)
	else
		DisableRagdoll(player)
	end
end)

you can use
local ragdoll = {}

to check if player is ragdoll or not

if ragdoll[player.Name] then
   -- is ragdoll
else
    -- is not ragdoll
end

when player ragdoll do this
ragdoll[player.Name] = true

This is probably the best solution. You can even just use player and I think that’ll also have it so the ragdoll information is garbage collected when the player leaves (because the Instance will be destroyed, but you should check if that’s true).

Destroying an instance does not remove its references (it just sets the instance’s parent to nil and disconnects whatever events it has). You would still have to set the player’s table key to nil to make sure the player instance gets garbage collected.

Yep! If I am making a ragdoll system, I will use plr instance instead of name cuz of preference but the reason why I use name here is due to the fact that plr reference will NOT be destroyed causing memory leak, a string also cause memory leak but the size of string is relatively smaller.

If you want to use plr instance
ragdoll[plr]
remember to set
ragdoll[plr] = nil
when player leaves to prevent memory leak
(actually also do it if you use string, it is good practice)

Would this be a valid-use scenario for a weak-keyed table?