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

Why when I press the key nothing happens?

Whenever I make the frame non visible before testing it to see if I press E and then nothing happens same for the elseif part of the script nothing happens what did I do wrong?

function onKeyDown(key)
key:lower() 
if key == "e" then
	script.Parent.Frame.Visible = true
elseif
	script.Parent.Frame.Visible == true then
	script.Parent.Frame.Visible = false
end
end
mouse.KeyDown:connect(onKeyDown) 

2 comments

0

Please, fix the tags. The question is not about GUIs, but User Input.

0

well the script is for a GUI so yes it is

2 answers

First, you need to get the mouse.

local mouse = game.Players.LocalPlayer:GetMouse()

However, there's two more problems with your code. You have,

key:lower()
if key == "e" then
    script.Parent.Frame.Visible = true
elseif
    script.Parent.Frame.Visible == true then
    script.Parent.Frame.Visible = false

key:lower() is useless. It does change the key to lower case, but the 'key' variable that you use later does not get lowered.

To fix this, do key = key:lower()

The second problem is the elseif. Remember, the key down event fires every time a key is pressed. For example, let's say we press a. Here's what the computer is doing: Well, key ~= "e", so we can't continue with that. Look! An elseif! Let's check that out! Hmm... well, the Frame is indeed visible, so let's make it invisible!

Therefore, every time a key is pressed it will make the Frame invisible. To fix this, we must do this:

if key == "e" and script.Parent.Frame.Visible == false then
    script.Parent.Frame.Visible = true
elseif
    key == "e" and script.Parent.Frame.Visible == true then
    script.Parent.Frame.Visible = false

Final code:

local mouse = game.Players.LocalPlayer:GetMouse()

function onKeyDown(key)
local key = key:lower() --Local variables are faster, thus reducing lag. 
if key == "e" and script.Parent.Frame.Visible == false then
    script.Parent.Frame.Visible = true
elseif
    key == "e" and script.Parent.Frame.Visible == true then
    script.Parent.Frame.Visible = false
end
end
mouse.KeyDown:connect(onKeyDown) 

Hope I helped!

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