An RemoteEvent is a one way asynchronous way of communication and data delivery. RemoteEvents can operate in three ways:
- Server > Client ( RemoteEvent:FireClient() )
- Client > Server ( RemoteEvent:FireServer() )
- Server > All Clients ( RemoteEvent:FireAllClients() )
For this tutorial, i will cover the basics of basics over how to use RemoteEvents.
Let's say, you wanted to utilize an RemoteEvent. Knowing that the server-client boundary can only be accessed through RemoteEvents and RemoteFunctions, we will need two scripts: one LocalScript and one Script.
In the script, you write this as to connect to the RemoteEvent in ReplicatedStorage (if it's named RemoteEvent):
-- Server Script
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RemoteEvent = ReplicatedStorage:WaitForChild("RemoteEvent")
wait(10) -- Wait function to ensure that the client loads before the event is fired
RemoteEvent:FireAllClients()
We successfully managed to connect to the RemoteEvent and fire it. But how can we interact with it?
In the LocalScript (recommended to place under StarterPlayerScripts), write this:
-- Local Script
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RemoteEvent = ReplicatedStorage:WaitForChild("RemoteEvent")
local function onEventFire()
print("Event received successfully")
end
RemoteEvent.OnServerEvent:Connect(onEventFire)
--[[
Output:
Event received succesfully
]]
An brief summary over how this works for the Server's side:
- Connect to the RemoteEvent in ReplicatedStorage
- Wait 10 seconds to ensure the client loads
- Fire the RemoteEvent
And for the client side:
- Connect to the RemoteEvent in ReplicatedStorage
- Create a function for when the Event is fired
- Connect the function to the RemoteEvent to detect when it is fired
- Run the function when the Event is fired
You can also use the parentheses in the RemoteEvent:FireAllClients() to transmit additional information (payload). For example:
-- Server Script
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RemoteEvent = ReplicatedStorage:WaitForChild("RemoteEvent")
wait(10) -- Wait function to ensure that the client loads before the event is fired
RemoteEvent:FireAllClients("This is the payload.")
-- Local Script
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RemoteEvent = ReplicatedStorage:WaitForChild("RemoteEvent")
local function onEventFire(payload)
print(payload)
end
RemoteEvent.OnServerEvent:Connect(onEventFire)
--[[
Output:
This is the payload.
]]
Note that there's more to RemoteEvents than this, although this is how RemoteEvents work to a fairly simplified point.