Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I make it so the sword does not duplicate?

Asked by 3 years ago
Edited 3 years ago

I made a script so if you touch a part you get a sword. I made it so you'll only get one sword. However, if you equip the sword it would give you an extra sword. How would I fix this? Here is the script:

script.Parent.Touched:Connect(function(hit)
    local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
    local sword = game.ReplicatedStorage.Sword:Clone()
    -- Detects if the part that 'hit' the brick contains a Humanoid
    wait()
    if plr.Backpack:FindFirstChild("Sword") then
    else
        if hit.Parent.Humanoid then
        -- Function GetPlayerFromCharacter returns the Character associated with the player (hit.Parent)
        -- Clones tool into player's backpack
        sword.Parent = plr.Backpack
    end

end
end)
0
Please put this in a code block so i can understand this more. Dexiber 272 — 3y
0
Fixed. SecretPax 20 — 3y

2 answers

Log in to vote
0
Answered by 3 years ago
Edited 3 years ago

check if the player already has the sword with

local player = game.Players.LocalPlayer
local hasSword = false

for _,v in pairs (player.Character:GetChildren()) do
    if v.Name ~= "Sword" then 
        hasSword = true
    end
end
for _,v in pairs (player.Backpack:GetChildren()) do
    if v.Name ~= "Sword" then 
        hasSword = true
    end
end

if hasSword then
    local sword = game.ReplicatedStorage.Sword:Clone()
    sword.Parent = player.Backpack
end

The reason you gotta check the player's backpack and character is that if the item is equipped it's parent is the character if it's not it's in the backpack.

0
When I run that it says, "Workspace.Area1.Strip1.Square.Script:4: attempt to index nil with 'Character' Workspace.Area1.Strip1.Square.Script:4: attempt to index nil with 'Character' SecretPax 20 — 3y
Ad
Log in to vote
0
Answered by
Dexiber 272 Moderation Voter
3 years ago
local deb = false

script.Parent.Touched:Connect(function(hit)
    local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
    local sword = game.ReplicatedStorage.Sword:Clone()
    local human = hit.Parent:FindFirstChild("Humanoid")
    -- Detects if the part that 'hit' the brick contains a Humanoid
    if human then
       if plr.Backpack:FindFirstChild("Sword") then
    else
            if not deb then
                deb = true
                sword.Parent = plr.Backpack
                wait(2)
                deb = false
        end
    end
    end
end)


i just copied and pasted your work here and edited it. (i also added a debounce)

0
Unfortunately it did not make a difference. However, is their a script to make it so you can't have more then 1 item? SecretPax 20 — 3y

Answer this question