I want this script inside a gui to check if a player has a tool. ROBLOX STUDIO

Viewed 621

Im making a Gui shop, inside this shop you can buy tools. I want to make it soo it doesn't give the tool if the player already has it in his inventory. I tried looking for an answer but i couldn't find one.

Here's the script :

player = script.Parent.Parent.Parent.Parent.Parent.Parent
money = player.leaderstats.Cash 
price = 100 
tool = game.Lighting:findFirstChild("Bigger")


function buy()
if money.Value >= price then
money.Value = money.Value - price
local tool1 = tool:clone()
tool1.Parent = player.Backpack
local tool2 = tool:clone()
        tool2.Parent = player.StarterGear
        

end
end
script.Parent.MouseButton1Down:connect(buy) ```
1 Answers

The solution I found consists of checking every item in the player's backpack and checking if it matches the tool name. Here is the code:

player = script.Parent.Parent.Parent.Parent.Parent.Parent
money = player.leaderstats.Cash 
price = 100 
tool = game.Lighting:findFirstChild("Bigger")


function buy()
    -- get's all items(tools) in the player's backpack
    local toolsinbackpack = player.Backpack:GetChildren() 
    -- get's the number of items(tools) in the player's backpack
    local numberoftools = table.getn(toolsinbackpack)
    local playerhasthetool = false
    for key = 1,numberoftools, 1 do
        -- check's if the tool in the player's backpack matches the name of the
        -- tool it want's to buy.
        if toolsinbackpack[key].Name == tool.Name then
            -- if the names match, the loop stops running and the variable is
            -- set to true 
            playerhasthetool = true
            break
        end
    end
    -- if the player has enough money and doesn't have the tool, it's allowed to
    -- buy the tool.
    if money.Value >= price and playerhasthetool == false then
        money.Value = money.Value - price
        local tool1 = tool:clone()
        tool1.Parent = player.Backpack
        local tool2 = tool:clone()
        tool2.Parent = player.StarterGear


    end
end
script.Parent.MouseButton1Down:connect(buy)

Note that if the player has the tool equipped(using the tool) while the script runs, it won't show up in its backpack, and he will be able to buy the tool 2 times. The player won't be able to buy the tool more than 2 times, though. For a perfect solution, you are going to need to check the player's model and see if the tool is in there. You can also do something so players need to unequip their tools before accessing the shop.

Related