Hey everyone,
I’m currently working on a script in Roblox that manages player interactions with a zone part. The goal is to give players a sword when they enter the zone and remove it when they leave. However, I’m facing an issue where the sword gets removed even when the player is just equipping it while still inside the zone.
Here’s a quick overview of how I have it set up:
- I use the
Touchedevent to give the sword to the player. - The
TouchEndedevent is meant to remove the sword when they leave.
The problem arises when a player equips the sword while in the zone. It seems that the equipping action might trigger the TouchEnded event, leading to the sword being removed unexpectedly.
local zonePart = script.Parent
local swordTemplate = game.ServerStorage:WaitForChild("Folder"):WaitForChild("ClassicSword")
local function giveSword(player)
local character = player.Character or player.CharacterAdded:Wait()
local backpack = player:WaitForChild("Backpack")
if not character:FindFirstChild("ClassicSword") and not backpack:FindFirstChild("ClassicSword") then
local swordClone = swordTemplate:Clone()
swordClone.Parent = backpack
end
end
local function removeSword(player)
local character = player.Character or player.CharacterAdded:Wait()
local backpack = player:WaitForChild("Backpack")
local swordInBackpack = backpack:FindFirstChild("ClassicSword")
local swordEquipped = character:FindFirstChild("ClassicSword")
if swordEquipped then
swordEquipped:Destroy()
elseif swordInBackpack then
swordInBackpack:Destroy()
end
end
zonePart.Touched:Connect(function(hit)
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
if player then
giveSword(player)
end
end)
zonePart.TouchEnded:Connect(function(hit)
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
if player then
removeSword(player)
end
end)