Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why is my keydown function working when the tool is unequipped?

I just finished my upgradeable teleport tool. To upgrade you press R on the keyboard. Fsr it works even when the tool is unequipped, which wouldnt work for my game because Im planning on adding other tools that also use r to upgrade. How can I make sure that it only functions if the tool is equipped? script:

repeat wait() until game.Players.LocalPlayer.Character
local Player = game.Players.LocalPlayer
local Body = Player.Character
local Mouse = Player:GetMouse()
local Level = script.Parent.Level.Value
local Cash = Player.leaderstats.Cash
local Tool = script.Parent
script.Parent.Activated:connect(function()
local Destination = Mouse.Hit
wait(5 - Level)
Body:MoveTo(Destination.p)
end)
Mouse.KeyDown:connect(function(k)
k = k:lower()
if k == "r" then
if Level < 5 then
if Cash.Value >= (Level * 5) then
Cash.Value = Cash.Value - (Level * 5)
Level = Level + 1
end
end
end
end)

1 answer

✓ Accepted answer

You need to actually make sure the tool is equipped before you process the user input. Added lines 8, 10, 16, and 27 - 32.

repeat wait() until game.Players.LocalPlayer.Character
local Player = game.Players.LocalPlayer
local Body = Player.Character
local Mouse = Player:GetMouse()
local Level = script.Parent.Level.Value
local Cash = Player.leaderstats.Cash
local Tool = script.Parent
local ToolIsEquipped
script.Parent.Activated:connect(function()
    if not ToolIsEquipped then return end
    local Destination = Mouse.Hit
    wait(5 - Level)
    Body:MoveTo(Destination.p)
end)
Mouse.KeyDown:connect(function(k)
    if not ToolIsEquipped then return end
    k = k:lower()
    if k == "r" then
        if Level < 5 then
            if Cash.Value >= (Level * 5) then
                Cash.Value = Cash.Value - (Level * 5)
                Level = Level + 1
            end
        end
    end
end)
Tool.Equipped:Connect(function()
    ToolIsEquipped = true
end)
Tool.Unequipped:Connect(function()
    ToolIsEquipped = false
end)

1 comment

0

Thanks!

This discussion is preserved as it was. New answers, comments, and votes are closed.