How do I make a local script activate a server script with a key down function? I know it has something to do with remote events/functions but I don't know how to use them. Please don't link to a wiki page, wiki links are blocked for me.
Objective: Activate a server script with a local script (.KeyDown()
event).
Solution: Remote Event or Function
Remote functions are recommended if you want to return a value back to the client. Otherwise, remote events are recommended.
REMOTE EVENT
:FireServer()
.OnServerEvent:connect(func)
-- LOCAL SCRIPT EXAMPLE Mouse = game.Players.LocalPlayer:GetMouse() RemoteEvent = game.ReplicatedStorage:WaitForChild("RemoteEvent") Mouse.KeyDown:connect(function (key) key = key:lower() if key == "f" then RemoteEvent:FireServer() end end
-- SERVER SCRIPT EXAMPLE RemoteEvent = Instance.new("RemoteEvent", game.ReplicatedStorage) function CallThisFunction() print("server called!") end RemoteEvent.OnServerEvent:connect(CallThisFunction) -- Literally almost like any other event
REMOTE FUNCTION
:InvokeServer()
function --[[RemoteFunction]].OnServerInvoke()
-- LOCAL SCRIPT EXAMPLE Mouse = game.Players.LocalPlayer:GetMouse() RemoteFunction = game.ReplicatedStorage:WaitForChild("RemoteFunction") Mouse.KeyDown:connect(function (key) key = key:lower() if key == "f" then print(RemoteFunction:InvokeServer()) end end
-- SERVER SCRIPT EXAMPLE RemoteFunction = Instance.new("RemoteFunction", game.ReplicatedStorage) function RemoteFunction.OnServerInvoke() return "server called!" end -- Literally almost like any other function
NOTE: Client to server communication means that an additional "player" argument will be included (first argument).
-- LOCAL RemoteEvent = game.ReplicatedStorage:WaitForChild("RemoteEvent") RemoteEvent:FireServer()
-- SERVER RemoteEvent = Instance.new("RemoteEvent", game.ReplicatedStorage) RemoteEvent.OnServerEvent:connect(function (player) print(player) end) -- OUTPUT: Player instance
Remote Event
CLIENT TO SERVER
:FireServer()
.OnServerEvent
SERVER TO CLIENT
:FireClient()
.OnClientEvent
Remote Function
CLIENT TO SERVER
:InvokeServer
.OnServerInvoke()
SERVER TO CLIENT
:InvokeClient
.OnClientInvoke
Unfortunately, this will be difficult to explain without using the wiki so here it goes:
Remote functions can be used to communicate between scripts, they're normally used with filteringenabled on. If you're not planning to use filtering enabled they can be sent via bind able events. However for arguments sake I will use remote functions.
You can send messages like this:
game.Workspace.RemoteFunction:InvokeServer(parameters)
And you can receive messages like this:
function game.Workspace.RemoteFunction.OnServerInvoke(ply,parameters) --code end
With Remote Functions the ply value is added automatically. If you wanted to send information back to a user you would have to use InvokeClient(ply,parameters) and receive messages via OnClientInvoke(parameters)
Any further questions? I'd be happy to answer them!