Script unequipping the sword even when they're still inside the part

  1. What do you want to achieve?
    A script to give and take swords from players that enter and leave the area.

  2. What is the issue?
    When players equip their sword, it automatically unequips it even when they’re inside the part.

  3. What solutions have you tried so far?
    Making it only fire if the part is the HumaoidRootPart.

local players = game:GetService("Players")

local parent = script.Parent
local sword = game:GetService("ServerStorage"):WaitForChild("Sword")

local playersInZone = {}

parent.Touched:Connect(function(part)
	if part.Parent:FindFirstChildOfClass("Humanoid") and part == part.Parent.PrimaryPart then
		local player = players:GetPlayerFromCharacter(part.Parent)
			
		if not table.find(playersInZone, player) then
			sword:Clone().Parent = player.Backpack
			table.insert(playersInZone, player)
		end
	end
end)

parent.TouchEnded:Connect(function(part)
	if part.Parent then
		local humanoid = part.Parent:FindFirstChildOfClass("Humanoid")
		
		if humanoid and part == part.Parent.PrimaryPart then
			local player = players:GetPlayerFromCharacter(part.Parent)

			if table.find(playersInZone, player) then
				humanoid:UnequipTools()
					
				if player.Backpack:FindFirstChild("Sword") then
					player.Backpack:FindFirstChild("Sword"):Destroy()
				end
					
				table.remove(playersInZone, playersInZone[player])
			end
		end
	end
end)

Did some quick research and found out that part.TouchEnded isn’t reliable so you must think of something else. This post also talks about that problem, maybe you find the solution in here helpful.

1 Like