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

Can you detect a key input on a server script?

The question says it all. I want to do this because I want a function on the server script to be activated when a key is pressed. How would I make this possible? This is the method that I tried(this was on the server side script)

function onKeyPress(input)
	if input.KeyCode == Enum.KeyCode.R then
		Reload()
	end
end
 
game:GetService("UserInputService").InputBegan:connect(onKeyPress)

1 answer

Well, UIS won't work on the server, so try using RemoteEvents or RemoteFunctions.

They are pretty similar, the main difference being RFunctions can return values and are accessed as functions instead of events. Example of both:

LocalScript

local reloadEvent = game.ReplicatedStorage.ReloadEvent -- etc. etc.

function onKeyPress(input)
    if input.KeyCode == Enum.KeyCode.R then
        reloadEvent:FireServer() -- or reloadFunction:InvokeServer()
    end
end

game:GetService("UserInputService").InputBegan:connect(onKeyPress)

ServerScript

local reloadEvent = game.ReplicatedStorage.ReloadEvent -- etc. etc.

reloadEvent.OnServerEvent:connect(function(clientFiredFrom)
	Reload()
end)

-- or

function reloadFunction.OnServerInvoke:connect(clientFiredFrom)
	Reload()
end

Hope I helped!

~TDP

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