--I'm attempting to make a script that spawns a part from a tool when i hit the key "e" Enabled = true wand = script.Parent stick = wand.Handle Player = script.Parent.Parent mouse = Player:GetMouse() function onKeyDown(key) if not Enabled then return end Enabled = false Key = key:lower() if key == "E" then x = Instance.new("Part") x.Parent = game.Workspace end Enabled = true function Lol(mouse) mouse.KeyDown:connect(function(key) onKeyDown(key, mouse) end) end end wand.Equipped:connect(Lol)
There are a few errors in this script. First of all, you call onKeyDown with two arguments, the mouse argument being unnecessary since it is already globally defined as a variable, not to mention the actual function has space for only one parameter of input. You can actually abbreviate your listening event line (line 22) by saying mouse.KeyDown:connect(onKeyDown)
which would directly attach your key parameter to the function when it is called.
Second, change your key == "E"
to Key == "e"
. Because you said Key = key:lower()
you should use this to your advantage and utilize the variable, since it will always be lowercase based on your definition. At the moment you are using the regular key
, the one that could be capital or lowercase.
Third, while I'm not sure of what your userdata looks like, Player = script.Parent.Parent
seems a little far fetched to me. I'm not sure WHERE this localscript is, but if it's underneath a tool/hopperbin object, which would be inside the Backpack, the Player would be three parents up, not two. You may want to check this; I could be completely wrong if you set it up differently.
Forth, your ends are positioned awkwardly. function Lol(mouse)
is only defined as a function when the function onKeyDown is called since the end for onKeyDown surround function Lol(mouse)
. To fix this, simply move the end on line 24 to the spot right before line 21 (where your other function starts). You may want to tab your code appropriately (indenting based on the level/hierarchy of code) so you can notice these encompass errors quicker.
This is what I have when I combine all these fixes to your code. I also added an Unequipped event to make sure the key doesn't work after the tool is deselected, and properly tabbed the code. This should make it easier to read, and I highly recommend you follow this format in future coding.
local Enabled = true local wand = script.Parent local stick = wand.Handle local Player = script.Parent.Parent local mouse = Player:GetMouse() local theconnector function onKeyDown(key) if not Enabled then return end Enabled = false local Key = key:lower() if Key == "e" then local x = Instance.new("Part", game.Workspace) end Enabled = true end function Lol() theconnector = mouse.KeyDown:connect(onKeyDown) end function NotLol() theconnector:disconnect() end wand.Equipped:connect(Lol) wand.Unequipped:connect(NotLol)
I hope this helped, and if it did, please make sure to upvote!