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

How to get a tool and remove a tool when using KeyDown?

Asked by
FiredDusk 1466 Moderation Voter
8 years ago

What I am trying to do is when you press 'q' then it gives you a gun but what I am wanting is if you press it again, it gets removed. I am not sure on how to do this. An explanation would be very helpful.

local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()
local Tool = game.ReplicatedStorage['Pistol']

Mouse.KeyDown:connect(function(Key)
    local NewKey = Key:lower()

    if NewKey == 'q' then
        Tool:Clone().Parent = Player.Backpack
    end
end)
0
I highly suggest using the UserInputService and looking at input began/ended. Mouse.KeyDown is outdated. jtefurd 50 — 8y

1 answer

Log in to vote
2
Answered by
StoIid 364 Moderation Voter
8 years ago
Edited 8 years ago

You would and should use arguments for this o.o

There are different ways you can go about doing this but I am going to use classical ole if statements cause I love those, they're nice :D

Anyways...

local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()
local Tool = game.ReplicatedStorage['Pistol']

Mouse.KeyDown:connect(function(Key)
    local NewKey = Key:lower()

    if NewKey == 'q' then
    if Player.Backpack:FindFirstChild('Pistol') == nil then --If the pistol is NOT in the backpack
        Tool:Clone().Parent = Player.Backpack --Puts the pistol in the players backpack
    elseif Player.Backpack:FindFirstChild('Pistol') ~= nil then --If the Pistol IS in the backpack
    Player.Backpack.Pistol:Destroy() --Destroys the pistol (removes it) c: 
    end
end -- almost forgot we needed to add an extra end (i think) to close off our extra if statement
end)

Explanation: The first if statement basically says if the Pistol is equal to nil (doesn't exist) then it'll put the tool (Pistol) in the players backpack. If the tool is not equal to nil('~=', is there) then it will destroy the Pistol.

Extra Info: You should always use :Destroy() when removing / deleting something with a script so that way it doesn't cause "zombies" in your code and hog up memory, which could cause lag if you use rusty old :remove() in too many scripts.

This is one of the many ways you can do this but I think this is the quickest way.

I hope this works, if not let me know!

Ad

Answer this question