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

Trying to trigger something with keys and getting errors. Any help?

Asked by
KDarren12 705 Donator Moderation Voter
5 years ago
Edited 5 years ago

I am trying to print "test" when the button "q" is pressed. Here is the code I'm using.

ms = game:GetService("Players").KDarren12:GetMouse()

ms.KeyDown:connect(function(key)
if key == "q" then
print('test')
end
end)

I get the error: "Attempt to index global 'ms' (a nil value)". Any help would be appreciated. Thank you.

Edit(I am using this code on a Client Side script, not a LocalScript.)

0
um there is server script and there is local script, server script is for the entire server to see and local script is for the local player to see Gameplayer365247v2 1055 — 5y

2 answers

Log in to vote
0
Answered by
Mr_Unlucky 1085 Moderation Voter
5 years ago

Currently using the KeyDown on a mouse is deprecated, instead you can be using stuff like ContextActionService or UserInputService.

local UIS = game:GetService("UserInputService")
UIS.InputBegan:Connect(functon(key)
    if key == Enum.UserInputType.Q then
        print("Test")
    end
end)

In the code above we have the service "UserInputService" in a variable. Every time someone taps a key or something the event "InputBegan" is fired. We use key for reference of the key that was touched and it that key is Q we print Test.

The article in case you want more info.

0
Thank you for the help :) KDarren12 705 — 5y
0
No problem! Mr_Unlucky 1085 — 5y
Ad
Log in to vote
0
Answered by 5 years ago
local KDarren12 = game.Players.FindFirstChild("KDarren12")
if KDarren12 then
local mouse = KDarren12:GetMouse()--u know these first 2

mouse.KeyDown:Connect(function(key)
    local Key = key.lower("q")--this sets the key
    if key == ("q") then--if u pressed q and it it matches the Key above then
        --what u want to happen in here
    end
end)
end

another method i think would work is this

local KDarren12 = game.Players:FindFirstChild("KDarren12")
if KDarren12 then--if it find the child KDarren12 then
game:GetService("UserInputService"):IsKeyDown:Connect(function(input, gameproceed)--gets ur input service aka the button u press
if input == (Enum.KeyCode.Q) then--if the button u press is q then
--what u want to happen in here
end
end)
end

Answer this question