Hi everyone,
I’m working on a sword pickup system, where only one player can pick up a sword at a time. The sword should respawn after the player holding it dies, and it can be picked up by the same player or a new one.
Here’s what I’m trying to achieve:
- When a player touches the sword, it should be picked up and added to their inventory (only one player can hold it at a time).
- When the player holding the sword dies, the sword should respawn at the same position.
- The respawned sword should be available for pickup again.
However, I’m encountering the following issues: The sword is being picked up multiple times by the player or other objects in the game. The sword is not respawning after the player dies.
Here is the code I’ve tried:
local sword = script.Parent
local respawnTime = 5
local swordPosition = sword.Handle.Position
local isSwordPickedUp = false
local function onPlayerDeath(player)
wait(respawnTime)
if not game.Workspace:FindFirstChild("Sword") then
local swordClone = sword:Clone()
swordClone.Parent = game.Workspace
swordClone.Handle.Position = swordPosition
swordClone.Handle.CanCollide = true
swordClone.Handle.Anchored = false
isSwordPickedUp = false
end
end
local function onSwordTouched(other)
if isSwordPickedUp then
return
end
local player = game:GetService("Players"):GetPlayerFromCharacter(other.Parent)
if player and other:IsDescendantOf(player.Character) and not player:FindFirstChild("HasSword") then
local swordClone = sword:Clone()
swordClone.Parent = player.Character
swordClone.Handle.Position = player.Character.HumanoidRootPart.Position
local tag = Instance.new("BoolValue")
tag.Name = "HasSword"
tag.Parent = player
isSwordPickedUp = true
end
end
game:GetService(“Players”).PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function(character)
character:WaitForChild(“Humanoid”).Died:Connect(function()
onPlayerDeath(player)
end)
end)
end)
sword.Handle.Touched:Connect(onSwordTouched)