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

How to make tool only usable while equipped?

Asked by 2 years ago

Right now I have made a gun tool. The only problem is that when I use any of the controls while it isn't equipped (like left clicking) it activates the gun. I tried to disable all of the scripts in the gun but it did not work.

1 answer

Log in to vote
0
Answered by
imKirda 4491 Moderation Voter Community Moderator
2 years ago

There are 2 events, Tool.Equipped and Tool.Unequipped, from name you can tell when they both fire, you can create variable called isEquipped, in Tool.Equipped set the variable to true and in Tool.Unequipped to false, in .Activated check if isEquipped is true before firing, this method is noob though, here is small code example:

local isEquipped = false

Tool.Activated:Connect(function()
    if not isEquipped then
        return -- Return will stop the function so it won't continue
    end

    print("Tool activated while equipped")
end)

Tool.Equipped:Connect(function()
    isEquipped = true
end)

Tool.Unequipped:Connect(function()
    isEquipped = false
end)

The better method is pro method, when you do Tool.Activated:Connect you are creating a connection, every time the event fires the connection is going to execute the connected function, you can disconnect this connection, this will stop it from executing the function, this is done using :Disconnect, every time user equips the tool you are going to connect the function as usual, but when he unequipps you are going to disconnect the connection:

-- We need to create variable here since "Unequipped" connection
-- needs to have access to the variable too
local activatedConnection

local function onToolActivated()
    print("Tool activated while equipped")
end

Tool.Equipped:Connect(function()
    -- ":Connect" returns the newly created connection
    activatedConnection = Tool.Activated:Connect(onToolActivated)
end)

Tool.Unequipped:Connect(function()
    activatedConnection:Disconnect()
end)
0
That worked thanks piggy0129 2 — 2y
Ad

Answer this question