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

Having trouble with a KeyDown function

It is supposed to tween a GUI onscreen when you press 'h'

g = script.Parent
f = g.Frame

p = game.Players.LocalPlayer
m = p.GetMouse()

function help()
	m.KeyDown:connect(function(key)
		if Key:byte() == 104 then
			f:TweenPosition(UDim2.new(0,100,0,250))
		end
	end)
end

coroutine.resume(couroutine.create(help))

4 answers

✓ Accepted answer

On line 9, Key is nil, while key is not.

Change Line 9 to: if key == "h" then. I personally prefer to use characters themselves in those cases, as it is more readable.

4 comments

0

Might want to lower (string.lower) the string too.

0

Why? There is no need for that. KeyDown will never fire with an uppercase key, at least, not as far as I know.

0

And - indeed - good point about line 5. It should be m = p:GetMouse(), not m = p.GetMouse(). This is possible but then you should pass pass first argument, which is strange (m = p.GetMouse(p))

0

Thanks

There are a few problems here.

p = game.Players.LocalPlayer
m = p.GetMouse()

GetMouse is a Method, therefore it needs to be called with a :

    m.KeyDown:connect(function(key)
        if Key:byte() == 104 then

You define the variable as keybut then used it as Key. Just change one or the other to match.

You also are randomly calling this as a coroutine? Why is that?

1 comment

0

I asked a friend if he could fix it before I came here and he edited it to that.

To add to Jobro's answer, there's no reason to set up your event inside of a function running in another thread. Events will run asynchronously. Also, remember that you can only use GetMouse in a LocalScript.

1 comment

0

It is in a LocalScript

In your code, the argument given to the function is stored in key. However, you use the variable Key in your if statement. Also, instead of converting key to a number, you can simply check if that variable key is equal to the string "h".

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