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

Inventory Item Keeps adding to backpack even after it is pressed. Someone please help me?

Asked by 5 years ago

So I have a Murder-Mystery-Style Inventory system, and whenever I press an imageButton, let's say the Default Knife, It correctly gives me the item, but if I press it again and again, it'll keep giving me the item! I have tried to make 2 scripts to prevent this, but neither of them are working.. so can someone PLEASE review them and tell me what I'm doing wrong?

Script 1:

script.Parent.MouseButton1Click:Connect(function()
    if game.Players.LocalPlayer.Backpack.DefKnife == true then
        return
    end
end)

Script 2:

script.Parent.MouseButton1Click:Connect(function()
    if game.Players.LocalPlayer.Backpack.DefKnife = game.Players.LocalPlayer.Backpack.DefKnife then
        return
    end
end)

And In case someone is wondering, here is the script to give the item:

script.Parent.MouseButton1Click:Connect(function()
    game.ReplicatedStorage.Tools.DefKnife:Clone().Parent = game.Players.LocalPlayer.Backpack
end)

1 answer

Log in to vote
0
Answered by
T0XN 276 Moderation Voter
5 years ago
Edited 5 years ago

One of the ways you can check if a folder such as the Backpack contains an object is by using :FindFirstChild()

Whenever you use FFC and the object is not found, it will return nil. Thus, if the statement used below returns nil, the tool will be given to the player.

local Player = game.Players.LocalPlayer
script.Parent.MouseButton1Click:Connect(function()
    if Player.Backpack:FindFirstChild("DefKnife") == nil then
        game.ReplicatedStorage.Tools.DefKnife:Clone().Parent = Player.Backpack
    end
end)

You can also use the not keyword within an if statement to verify that the Backpack doesn't already contain the tool.

script.Parent.MouseButton1Click:Connect(function()
    if not Player.Backpack:FindFirstChild("DefKnife") then
        game.ReplicatedStorage.Tools.DefKnife:Clone().Parent = Player.Backpack
    end
end)
0
Yes! Thank you sooo much! I have been looking for a script to do this for so long! :D SBlankthorn 329 — 5y
Ad

Answer this question