Multiplayer, saving and debugging, lesson 27
RemoteEvents
Goal: Send messages between a player's device and the server.
about 7 min4 practice exercises
The client and the server cannot call each other's functions directly. They send messages through a RemoteEvent. Put it in ReplicatedStorage so both sides can find it.
1. Client asks
buyEvent:FireServer("Boots")2. Server checks
OnServerEvent(player, item)Known item? Enough coins? Too soon?
3. Client shows it
OnClientEvent(newTotal)Client to server. The client fires, the server listens:
-- LocalScript (client)
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local buyEvent = ReplicatedStorage:WaitForChild("BuyItem")
buyEvent:FireServer("SpeedBoots")
-- Script (server)
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local buyEvent = ReplicatedStorage.BuyItem
buyEvent.OnServerEvent:Connect(function(player, itemName)
print(player.Name .. " wants to buy " .. itemName)
end)
The client sent one value, but the server function receives two. Roblox always adds the player who fired as the first parameter. The client cannot fake it, which is what lets you trust who is asking.
Server to client goes the other way:
-- Script (server)
coinsChanged:FireClient(player, 25) -- one player
announce:FireAllClients("Round over") -- everyone
-- LocalScript (client)
coinsChanged.OnClientEvent:Connect(function(newTotal)
print("You now have " .. newTotal .. " coins")
end)
On the client there is no player parameter, because the client already knows who it is.
Sources
Checked against Roblox's documentation on . The lesson is in our own words; these pages are the source of truth.