要点
RemoteEvent 是一个通常放在 ReplicatedStorage 中的对象,用来跨越客户端和服务端之间的边界传递消息。LocalScript 调用 FireServer,服务端在 OnServerEvent 中收到消息,第一个参数是自动加上的发送者 Player。服务端调用 FireClient(player, ...) 或 FireAllClients(...),LocalScript 在 OnClientEvent 中收到消息。
- 只有当客户端需要得到答复时才使用 RemoteFunction(
InvokeServer和OnServerInvoke)。避免使用InvokeClient:客户端出错、退出或者一直不返回值,都会让服务端的调用出问题。 - 永远不要相信客户端发来的东西。在服务端检查每个参数的类型、范围和归属,玩家的距离,以及他调用 Remote 的频率。
- 函数、元表以及另一方看不到的对象在传递过程中都无法保留。UnreliableRemoteEvent 可能丢失消息或打乱顺序,并且会丢弃任何超过 1000 字节的数据。
本页内容
为什么需要 RemoteEvent
每个 Roblox 游戏都由一个服务端加上每名玩家各一个客户端组成。这里服务端说了算:只有服务端创建的新对象或修改的属性才会到达所有玩家。在 LocalScript 中做的修改只留在一台设备上,只有少数例外,比如玩家自己的角色,它的移动由他的客户端控制。所以当一次点击或按键需要改变共享的世界时,客户端必须请求服务端;而当服务端希望某个玩家的屏幕做出反应时,它必须通知这个客户端。如果你还不熟悉 Script 和 LocalScript 的区别,请先阅读 Script vs LocalScript vs ModuleScript(英文)。如果脚本编程本身对你来说还是新东西,请先从 如何在 Roblox Studio 中写脚本 开始。
为了跨越这条边界,Roblox 提供了三种对象:
- RemoteEvent:单向消息。发送方立即继续执行。
- RemoteFunction:等待答复的请求。调用的代码会暂停,直到另一方返回值。
- UnreliableRemoteEvent:单向消息,可能丢失或乱序到达,但网络负担更小。适合不停变化的数据。
| 方向 | 发送方调用 | 接收方连接到 | 接收方收到 |
|---|---|---|---|
| 从客户端到服务端 | LocalScript 中的 remote:FireServer(...) | Script 中的 remote.OnServerEvent | 发送消息的 Player,然后是你的参数 |
| 从服务端到一个客户端 | Script 中的 remote:FireClient(player, ...) | LocalScript 中的 remote.OnClientEvent | 只有你的参数 |
| 从服务端到所有客户端 | Script 中的 remote:FireAllClients(...) | LocalScript 中的 remote.OnClientEvent | 只有你的参数 |
| 客户端提问,服务端回答 | remoteFunction:InvokeServer(...) | remoteFunction.OnServerInvoke = function(player, ...) | Player,然后是你的参数。调用方得到函数返回的值 |
客户端之间不能直接发送消息。要把某个玩家的东西传给其他人,先发送到服务端,在那里检查,再由服务端通过 FireClient 或 FireAllClients 转发。按照 Roblox 的安全建议,服务端在这里扮演的是把关者,而不是简单的转发器。
Remote 放在哪里
Remote 必须放在服务端和客户端都能看到的地方。通常的位置是 ReplicatedStorage;Roblox 文档提到,某些情况下 Workspace 或 Tool 也可以。ServerStorage 和 ServerScriptService 只有服务端能访问,所以在那里等待 Remote 的 LocalScript 会永远等下去。
- 在 Explorer 中把鼠标悬停在 ReplicatedStorage 上,点击 + 按钮,插入一个 Folder。把文件夹命名为
Remotes。 - 把鼠标悬停在
Remotes上,点击 +,插入一个 RemoteEvent。给它起一个说明用途的名字,例如PaintRequest。 - 为每个 Remote 重复这一步。本教程使用两个 RemoteEvent(
PaintRequest和Notify)和一个 RemoteFunction(RedeemCode)。
ReplicatedStorage
Remotes Folder new
PaintRequest RemoteEvent new
Notify RemoteEvent new
RedeemCode RemoteFunction new
ServerScriptService
PaintServer Script new
WelcomeServer Script new
FinishAnnouncer Script new
RedeemServer Script new
RemoteGuard ModuleScript new
StarterPlayer
StarterPlayerScripts
PaintClient LocalScript new
NotifyClient LocalScript new
StarterGui
CodeGui ScreenGui new
CodeBox TextBox new
RedeemClient LocalScript new
Workspace
Paintable Folder new
FinishLine Part new
本教程中的脚本通过 WaitForChild 查找 Remote。如果 Remote 已经在那里,它会立即返回结果;如果还没有,它会等待,例如服务端脚本在游戏运行时才创建 Remote 的情况。每种请求单独用一个 Remote:这样每个服务端处理函数只需要检查一种参数形式,比一个 Remote 包揽所有情况要容易做对得多。
模式 1:从客户端到服务端,由服务端检查
最常见的任务:玩家在自己的屏幕上做了某件事,由服务端决定会发生什么。这里玩家按 Q 从四种颜色中选一种,然后点击或轻触零件给它上色。所有人都能看到新颜色,因为上色的是服务端。
客户端发送两样东西:哪个零件,以及颜色的编号。它从不发送颜色本身;同样,在其他游戏中它也不应该发送价格、奖励或伤害数值。被修改过的客户端可以发送任何东西,所以真实的数据(这里是调色板)由服务端保存,而参数只被当作需要检查的请求。
- 在 Workspace 中插入一个名为
Paintable的 Folder,在里面放几个锚定的 Part。 - 确认
ReplicatedStorage.Remotes中有一个名为PaintRequest的 RemoteEvent。 - 在 ServerScriptService 中插入一个名为
PaintServer的 Script,在 StarterPlayer、StarterPlayerScripts 中插入一个名为PaintClient的 LocalScript,写入下面的代码。
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local remotes = ReplicatedStorage:WaitForChild("Remotes")
local paintRequest = remotes:WaitForChild("PaintRequest") :: RemoteEvent
local paintable = workspace:WaitForChild("Paintable")
-- 颜色属于服务端。客户端只发送一个编号,用来从中选择一种。
local PALETTE = {
Color3.fromRGB(231, 76, 60),
Color3.fromRGB(46, 204, 113),
Color3.fromRGB(52, 152, 219),
Color3.fromRGB(241, 196, 15),
}
local MAX_DISTANCE = 30 -- 角色与零件之间的 stud 数
local COOLDOWN_SECONDS = 0.25
local lastPaint: { [Player]: number } = {}
-- 第一个参数始终是调用 Remote 的玩家。它由 Roblox 填入,
-- 所以可以信任。它后面的一切都来自客户端,不能信任。
paintRequest.OnServerEvent:Connect(function(player: Player, part: unknown, colourIndex: unknown)
-- 1. 类型:真正的零件,而不是伪装成零件的表
if typeof(part) ~= "Instance" or not part:IsA("BasePart") then
return
end
-- 2. 范围:1 到 4 之间的整数。NaN 和无穷大也在这里被过滤掉。
if type(colourIndex) ~= "number" or not math.isfinite(colourIndex) then
return
end
if colourIndex % 1 ~= 0 or colourIndex < 1 or colourIndex > #PALETTE then
return
end
-- 3. 允许的目标:只有 Paintable 文件夹中的零件,游戏中的其他东西都不行
if not part:IsDescendantOf(paintable) then
return
end
-- 4. 距离:玩家的角色必须在零件附近
local character = player.Character
local root = character and character:FindFirstChild("HumanoidRootPart")
if not (root and root:IsA("BasePart")) then
return
end
if (root.Position - part.Position).Magnitude > MAX_DISTANCE then
return
end
-- 5. 频率限制:每名玩家每四分之一秒只能上色一次
local now = os.clock()
local last = lastPaint[player]
if last and now - last < COOLDOWN_SECONDS then
return
end
lastPaint[player] = now
part.Color = PALETTE[colourIndex]
end)
Players.PlayerRemoving:Connect(function(player: Player)
lastPaint[player] = nil
end)
每一项没通过的检查都只是 return。没有必要向作弊的客户端解释它为什么被拒绝。
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local UserInputService = game:GetService("UserInputService")
local remotes = ReplicatedStorage:WaitForChild("Remotes")
local paintRequest = remotes:WaitForChild("PaintRequest") :: RemoteEvent
local paintable = workspace:WaitForChild("Paintable")
local COLOUR_COUNT = 4 -- 真正的颜色保存在服务端
local selectedColour = 1
-- 射线只能命中 Paintable 文件夹中的零件
local rayParams = RaycastParams.new()
rayParams.FilterType = Enum.RaycastFilterType.Include
rayParams.FilterDescendantsInstances = { paintable }
UserInputService.InputBegan:Connect(function(input: InputObject, gameProcessed: boolean)
if gameProcessed then
return -- 这次按键或点击进了聊天框或按钮
end
if input.KeyCode == Enum.KeyCode.Q then
selectedColour = selectedColour % COLOUR_COUNT + 1
return
end
local isClick = input.UserInputType == Enum.UserInputType.MouseButton1
local isTap = input.UserInputType == Enum.UserInputType.Touch
if isClick or isTap then
local camera = workspace.CurrentCamera
local ray = camera:ScreenPointToRay(input.Position.X, input.Position.Y)
local result = workspace:Raycast(ray.Origin, ray.Direction * 500, rayParams)
if result then
-- 是请求,不是命令:上不上色由服务端决定
paintRequest:FireServer(result.Instance, selectedColour)
end
end
end)
当引擎已经处理了这次输入时,gameProcessed 为 true,通常是在界面中:点击按钮,或者在聊天栏这样的文本框中输入按键。有了这个检查,在消息里输入字母 Q 就不会切换颜色。
模式 2:从服务端到一个客户端
服务端通过 FireClient 给一名玩家发送消息。第一个参数是消息要发给的 Player,客户端的处理函数只收到它后面的参数。所有私人的东西都用它:通知、奖励弹窗、只有这名玩家应该听到的声音。过场动画教程 是一个更大的完整示例:服务端决定玩家何时观看过场动画,通过 FireClient 把镜头帧发给这一名玩家,镜头则由他的设备来移动。
这对脚本会在玩家进入时显示一条欢迎语。LocalScript 自己搭建一个小横幅,所以不需要设置 GUI。
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local notify = ReplicatedStorage:WaitForChild("Remotes"):WaitForChild("Notify") :: RemoteEvent
local function welcome(player: Player)
-- 第一个参数选择由哪个客户端接收消息。其他人都看不到它。
notify:FireClient(player, `Welcome, {player.DisplayName}! Press Q to change colour.`)
end
Players.PlayerAdded:Connect(welcome)
-- 在 Studio 中你可能比这个脚本先连接进入游戏,所以也欢迎已经在场的所有人
for _, player in Players:GetPlayers() do
welcome(player)
end
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local notify = ReplicatedStorage:WaitForChild("Remotes"):WaitForChild("Notify") :: RemoteEvent
local player = Players.LocalPlayer
-- 屏幕顶部的小横幅,用代码搭建
local gui = Instance.new("ScreenGui")
gui.Name = "Notifications"
gui.ResetOnSpawn = false
gui.Parent = player:WaitForChild("PlayerGui")
local label = Instance.new("TextLabel")
label.AnchorPoint = Vector2.new(0.5, 0)
label.Position = UDim2.new(0.5, 0, 0, 16)
label.Size = UDim2.fromOffset(420, 44)
label.BackgroundColor3 = Color3.fromRGB(18, 11, 31)
label.TextColor3 = Color3.new(1, 1, 1)
label.TextScaled = true
label.Visible = false
label.Parent = gui
local messageCount = 0
-- 这里没有 player 参数:服务端已经选好了谁接收消息
notify.OnClientEvent:Connect(function(message: string)
messageCount += 1
local thisMessage = messageCount
label.Text = message
label.Visible = true
task.delay(4, function()
if messageCount == thisMessage then -- 如果没有被更新的消息替换,就隐藏
label.Visible = false
end
end)
end)
服务端在 PlayerAdded 时发送消息,这可能发生在这个 LocalScript 连接处理函数之前。这没关系:Roblox 会把处理函数出现之前到达的 RemoteEvent 消息排进队列,处理函数一连接就按顺序送达。
客户端不需要防备服务端:只有服务端代码才能触发 OnClientEvent。message: string 这个注解是给类型检查用的,不是运行时的检查。
模式 3:从服务端到所有客户端
FireAllClients 把同一条消息发给每个已连接的玩家。它没有 Player 参数,每个客户端都在和之前一样的 OnClientEvent 中收到消息,所以模式 2 的 NotifyClient 脚本已经能显示它了。
这个 Script 会在玩家第一次碰到终点线时向所有人宣布。在 Workspace 中添加一个名为 FinishLine 的锚定 Part,然后在 ServerScriptService 中添加 Script。
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local notify = ReplicatedStorage:WaitForChild("Remotes"):WaitForChild("Notify") :: RemoteEvent
local finishLine = workspace:WaitForChild("FinishLine") :: BasePart
local finished: { [Player]: boolean } = {}
finishLine.Touched:Connect(function(hit: BasePart)
local character = hit:FindFirstAncestorOfClass("Model")
local player = character and Players:GetPlayerFromCharacter(character)
if not player or finished[player] then
return -- 不是玩家,或者已经宣布过了
end
finished[player] = true
-- 每个已连接的客户端都会用这段文字运行自己的 OnClientEvent 处理函数
notify:FireAllClients(`{player.DisplayName} reached the finish!`)
end)
Players.PlayerRemoving:Connect(function(player: Player)
finished[player] = nil
end)
作弊者可以在任意距离为自己的角色触发 Touched,但对于每名玩家只显示一次的公告来说,这无害。如果以后要为到达终点发放奖励,请在发放之前加上服务端检查,例如距离回合开始的最短时间。
FireAllClients 只会到达此刻已连接的玩家。晚一秒进入的人就看不到这条消息了。这适合一次性的时刻,比如公告、爆炸特效或声音,但不适合回合计时器或当前游戏阶段这样的状态。对于状态,请在服务端设置一个属性(attribute),例如 ReplicatedStorage:SetAttribute("TimeLeft", 30),然后在客户端用 GetAttribute 和 GetAttributeChangedSignal("TimeLeft") 读取。属性会复制到每个客户端,包括后来进入的玩家。
RemoteFunction:当客户端需要答复时
RemoteEvent 的原则是“发出去就不管了”。RemoteFunction 会让调用方等待:InvokeServer 会暂停调用它的代码,直到服务端的 OnServerInvoke 函数返回值,然后交回它返回的东西。当客户端没有答复就无法继续时使用它,例如“这个兑换码对不对?”。如果不需要答复,Roblox 推荐使用 RemoteEvent,因为它不会等待。
示例:一个让玩家输入兑换码的输入框。服务端保存兑换码,检查文本,并返回两个值:是否成功,以及要显示的消息。
- 在
ReplicatedStorage.Remotes中插入一个名为RedeemCode的 RemoteFunction。 - 在 StarterGui 中插入一个名为
CodeGui的 ScreenGui,在里面插入一个名为CodeBox的 TextBox。大小和位置随你喜欢。 - 把下面的 Script 添加到 ServerScriptService,把 LocalScript 放进
CodeBox里面。
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local redeemCode = ReplicatedStorage:WaitForChild("Remotes"):WaitForChild("RedeemCode") :: RemoteFunction
-- 兑换码保存在服务端,任何玩家都读不到
local CODES: { [string]: number } = {
LAUNCH = 100,
THANKYOU = 50,
}
local MAX_LENGTH = 20
local COOLDOWN_SECONDS = 2
local usedCodes: { [Player]: { [string]: boolean } } = {}
local lastTry: { [Player]: number } = {}
-- 用 = 赋值。OnServerInvoke 是回调,不是用 Connect 连接的事件。
redeemCode.OnServerInvoke = function(player: Player, code: unknown): (boolean, string)
local now = os.clock()
local last = lastTry[player]
if last and now - last < COOLDOWN_SECONDS then
return false, "Wait a moment before trying again"
end
lastTry[player] = now
if type(code) ~= "string" or #code == 0 or #code > MAX_LENGTH then
return false, "Type a code first"
end
local key = string.upper(code)
local reward = CODES[key]
if not reward then
return false, "That code doesn't exist"
end
local used = usedCodes[player]
if not used then
used = {}
usedCodes[player] = used
end
if used[key] then
return false, "You already used that code"
end
local leaderstats = player:FindFirstChild("leaderstats")
local coins = leaderstats and leaderstats:FindFirstChild("Coins")
if not (coins and coins:IsA("IntValue")) then
return false, "Coins aren't set up in this game yet"
end
used[key] = true
coins.Value += reward
return true, `Code accepted: +{reward} coins`
end
Players.PlayerRemoving:Connect(function(player: Player)
usedCodes[player] = nil
lastTry[player] = nil
end)
它会增加 排行榜教程 中的 Coins 数据。用过的兑换码只记到玩家离开为止,所以按现在的写法,玩家可以重新进入游戏再次输入同一个兑换码。如果金币是会保存的,这就等于每次重新进入都能白拿金币:在正式游戏中使用之前,请把每名玩家用过的兑换码和他的存档数据一起保存在 数据存储 中。
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local redeemCode = ReplicatedStorage:WaitForChild("Remotes"):WaitForChild("RedeemCode") :: RemoteFunction
local box = script.Parent :: TextBox
local GREEN = Color3.fromRGB(46, 204, 113)
local RED = Color3.fromRGB(231, 76, 60)
box.FocusLost:Connect(function(enterPressed: boolean)
local code = box.Text
if not enterPressed or code == "" then
return
end
box.Text = ""
box.PlaceholderText = "Checking..."
-- InvokeServer 会暂停这个函数,直到服务端的回调返回值。
-- 如果调用失败,pcall 可以防止 LocalScript 停止运行。
local ok, accepted, message = pcall(function()
return redeemCode:InvokeServer(code)
end)
if ok and type(message) == "string" then
box.PlaceholderText = message
box.PlaceholderColor3 = if accepted == true then GREEN else RED
else
box.PlaceholderText = "Something went wrong, try again"
box.PlaceholderColor3 = RED
end
end)
一个 RemoteFunction 只有一个服务端回调。如果两个脚本都给同一个 RemoteFunction 设置了 OnServerInvoke,只有最后一个生效。
InvokeClient 的危险
RemoteFunction 也可以反过来用,服务端用 InvokeClient,客户端用 OnClientInvoke。Roblox 文档列出了三个严重的风险:
- 如果客户端的回调出错,服务端也会出错。
- 如果玩家在调用期间退出,
InvokeClient会出错。 - 如果客户端一直不返回值,服务端脚本会永远等下去。
被修改过的客户端控制着自己的回调,所以作弊者可以故意制造第三种情况,想卡住这个服务端线程多久就卡多久。要更新玩家的屏幕,请使用 FireClient。如果服务端确实需要客户端的信息,就发送一个 RemoteEvent,让客户端通过另一个 RemoteEvent 回复,并在服务端把没有回复当作正常情况处理。
在服务端检查每个参数
作弊者可以用任意参数、任意次数地调用任何 RemoteEvent 或 RemoteFunction。唯一不能伪造的是第一个参数:发送消息的 Player 由 Roblox 自己填入。之后的一切都必须在服务端采取行动之前检查。把 Remote 藏起来或者在 LocalScript 中检查都没有用,因为作弊者控制着自己的客户端。
| 检查 | 服务端要问的问题 | 示例 |
|---|---|---|
| 类型 | 这是我期望的类型吗?是 Instance,而不是被拼凑得像它的表? | typeof(part) == "Instance" and part:IsA("BasePart") |
| 范围 | 数字是有限的并且在允许的范围内吗?文本的长度合理吗? | math.isfinite(n)、n >= 1 and n <= 4、#text <= 20 |
| 归属 | 这名玩家拥有这件物品吗?他的钱够吗?他有权对这个对象操作吗? | 物品在他的背包里;零件位于 Paintable 中 |
| 距离 | 在服务端的世界副本中,玩家的角色离得够近吗?给延迟留一点余量。 | 离零件不超过 30 个 stud |
| 频率 | 这名玩家发送得是不是太频繁了? | 每名玩家的冷却时间,或可累积调用次数的限制 |
NaN 值得单独提醒。它是数字,所以 type(x) == "number" 能通过,但和它的任何比较结果都是 false,像 x < 0 or x > 100 这样的检查会让它直接通过。math.isfinite(x) 会拒绝 NaN 和正负无穷大。
记住距离检查的局限。每个客户端控制自己角色的物理,所以作弊者可以在调用之前把角色移动到目标旁边。这个检查仍然能阻止最简单的滥用,也就是站在一个地方对整张地图操作。让作为目标的零件保持锚定:Roblox 的安全文档指出,作弊者可以获得自己附近未锚定零件的网络所有权并把它们拉近,这会绕过距离检查。
下面是做成 ModuleScript 的同一套检查,可以在每个 Remote 处理函数中使用。
local Players = game:GetService("Players")
local RemoteGuard = {}
-- min 和 max 之间的真正数字。拒绝 NaN 和无穷大,它们能通过
-- 普通的 type(x) == "number" 检查。
function RemoteGuard.number(value: unknown, min: number, max: number): number?
if type(value) ~= "number" or not math.isfinite(value) then
return nil
end
if value < min or value > max then
return nil
end
return value
end
-- min 和 max 之间的整数,用于数量、索引和计数
function RemoteGuard.integer(value: unknown, min: number, max: number): number?
local n = RemoteGuard.number(value, min, max)
if n and n % 1 == 0 then
return n
end
return nil
end
-- 限制长度的文本。对于无效的 UTF-8,utf8.len 返回 nil,
-- 而数据存储会拒绝这种文本。
function RemoteGuard.text(value: unknown, maxLength: number): string?
if type(value) ~= "string" or #value > maxLength or utf8.len(value) == nil then
return nil
end
return value
end
-- 位于你允许的容器中、属于预期类的 Instance。
-- 被拼凑得像 Instance 的表无法通过 typeof 检查。
function RemoteGuard.instanceIn(value: unknown, className: string, container: Instance): Instance?
if typeof(value) ~= "Instance" then
return nil
end
if not value:IsA(className) or not value:IsDescendantOf(container) then
return nil
end
return value
end
-- 当玩家的角色离 position 不超过 maxDistance 个 stud 时为 true
function RemoteGuard.isNear(player: Player, position: Vector3, maxDistance: number): boolean
local character = player.Character
local root = character and character:FindFirstChild("HumanoidRootPart")
if not (root and root:IsA("BasePart")) then
return false
end
return (root.Position - position).Magnitude <= maxDistance
end
-- 每名玩家的频率限制。每名玩家可以一次连续调用 `burst` 次,
-- 每秒恢复 `perSecond` 次。返回一个在执行操作前调用的函数:
-- 它回答 true(可以)或 false(太频繁)。
function RemoteGuard.limiter(burst: number, perSecond: number): (Player) -> boolean
local buckets: { [Player]: { tokens: number, updated: number } } = {}
Players.PlayerRemoving:Connect(function(player: Player)
buckets[player] = nil
end)
return function(player: Player): boolean
local now = os.clock()
local bucket = buckets[player]
if not bucket then
bucket = { tokens = burst, updated = now }
buckets[player] = bucket
end
bucket.tokens = math.min(burst, bucket.tokens + (now - bucket.updated) * perSecond)
bucket.updated = now
if bucket.tokens < 1 then
return false
end
bucket.tokens -= 1
return true
end
end
return RemoteGuard
把它放在 ServerScriptService 中。那里的代码永远不会到达客户端,所以没人能读到你的检查。
下面是用它改写的模式 1 的处理函数。替换 PaintServer 的内容:
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerScriptService = game:GetService("ServerScriptService")
-- ":: any" 只对 Luau 的严格类型检查有意义;运行时它不改变任何东西
local RemoteGuard = require(ServerScriptService:WaitForChild("RemoteGuard")) :: any
local paintRequest = ReplicatedStorage:WaitForChild("Remotes"):WaitForChild("PaintRequest") :: RemoteEvent
local paintable = workspace:WaitForChild("Paintable")
local PALETTE = {
Color3.fromRGB(231, 76, 60),
Color3.fromRGB(46, 204, 113),
Color3.fromRGB(52, 152, 219),
Color3.fromRGB(241, 196, 15),
}
local canPaint = RemoteGuard.limiter(4, 4) -- 一次最多 4 次,之后每秒 4 次
paintRequest.OnServerEvent:Connect(function(player: Player, partArg: unknown, colourArg: unknown)
local part = RemoteGuard.instanceIn(partArg, "BasePart", paintable) :: BasePart?
local colourIndex = RemoteGuard.integer(colourArg, 1, #PALETTE) :: number?
if not part or not colourIndex then
return
end
if not RemoteGuard.isNear(player, part.Position, 30) or not canPaint(player) then
return
end
part.Color = PALETTE[colourIndex]
end)
玩家离开时,限制器会删除他的记录,所以它的表不会在服务器的整个生命周期里一直增长。
在武器中这些检查最重要:永远不要让客户端告诉服务端打中了谁。剑的教程 中的 Remote 根本不带参数,由服务端自己寻找目标。枪的教程 只发送瞄准点,服务端先检查它的类型、NaN 和距离,再发射自己的射线。
菜单也遵循同样的规则:发送选择,而不是结果。在 NPC 对话教程 中,客户端只发送被点击按钮的编号,服务端自己查看这个回答会给什么。传送教程 中的菜单发送的是传送点的名字而不是位置,服务端在自己的文件夹中找到这个点,并检查它需要多少 Wins。
能发送什么,不能发送什么
可以传递数字、字符串、布尔值,Vector3、CFrame、Color3 和 Enum 项等 Roblox 类型,双方都能看到的 Instance,以及由这些组成的表。有些值在传递过程中会改变或消失:
| 你发送 | 会发生什么 |
|---|---|
| 函数 | 另一方收到 nil |
| 带元表的表 | 元表会丢失,表只通过元表才具有的一切也随之丢失 |
| 数字键和字符串键混合的表 | Roblox 建议不要这样做:请发送纯数组或纯字典 |
内部含有 nil 值的表 | 避免这样做:Roblox 不建议在任何索引处放 nil |
| 键为 Instance、userdata 或 function 类型的表 | 这些键会变成字符串 |
| 接收方看不到的 Instance,例如来自 ServerStorage 的,或在 LocalScript 中创建的 | 另一方收到 nil |
| 任何表 | 接收方得到的是副本,而不是同一张表 |
一个好习惯:发送标识,而不是对象或数值。物品的名称、选项的编号、服务端能够找到并检查的零件。剩下的由服务端用自己的数据来处理。
为什么 RemoteFunction 返回 nil
如果 InvokeServer 给你的是 nil,请按顺序检查以下几点:
- 没有返回值的路径。
OnServerInvoke的每一个出口都必须返回点什么。提前检查中的空return会送回nil。 - 嵌套函数中的 return。
pcall(function() ... end)、:Connect处理函数或task.spawn中的return只会退出这个内部函数。把结果保存下来,例如local ok, data = pcall(...),然后从回调本身返回data。 - 无法跨越边界的值。函数或客户端看不到的 Instance(例如 ServerStorage 中的任何东西)到达时都是
nil。启用 instance streaming 时,服务端刚创建的零件可能在函数返回时还没有到达客户端。 - 回调被另一个脚本设置了。只有最后一次对
OnServerInvoke的赋值生效。在你的脚本里搜索这个 Remote 的名字。
如果调用根本不返回,说明还没有任何脚本设置 OnServerInvoke(Roblox 会把调用排在队列里,直到它被设置),或者回调卡住了,例如在 WaitForChild 上等待一个永远不会出现的东西。
UnreliableRemoteEvent:用于持续的一次性更新
UnreliableRemoteEvent 拥有和 RemoteEvent 相同的方法和事件:FireServer、FireClient、FireAllClients、OnServerEvent 和 OnClientEvent。区别在于 Roblox 既不保证送达,也不保证顺序。在以下情况下,消息可能被丢弃且不会重发:
- 它在途中丢失,或在拥堵的网络中等待太久
- 它的数据超过 1000 字节
- 客户端发送得比限制更频繁(多余的被丢弃,而不是延后)
- 到达时没有连接任何处理函数(它被丢掉,而不是排进队列)
消息也可能乱序到达,它们的顺序和你的 RemoteEvent 或 RemoteFunction 没有任何关系。当只有最新的值重要、下一次更新会在几分之一秒后到来时使用它:玩家瞄准的方向、装饰性特效的位置、每一帧都在变化的值。如果顺序很重要,就在每条消息里放一个序号或时间戳,并忽略比最后处理的那条更旧的一切。
永远不要把它用于必须恰好发生一次的事情,例如购买、伤害、奖励或回合开始。并且要像对 RemoteEvent 一样,在服务端检查它的参数。
送达顺序和频率限制
Roblox 的送达保证针对的是单个方向上的单个连接:从服务端到一个客户端,或从一个客户端到服务端。
- RemoteEvent 是可靠且有序的。只要接收方保持连接,丢失的消息就会重发,消息会按照你发送的顺序到达,即使经过不同的 RemoteEvent 也是如此。如果服务端给玩家先发 A,再发 B,再发 A,这名玩家收到的就是 A、B、A。
- 顺序指的是处理函数开始运行的时刻。如果处理函数让出控制权,例如通过
task.wait或WaitForChild,下一条消息可能在第一条处理完之前就开始处理。 - RemoteFunction 和 RemoteEvent 之间没有顺序保证。如果你的代码依赖严格的顺序,就通过同一种类型的 Remote 发送相关消息,或者加上你自己的序号。
- 属性和 attribute 的变化相对于 Remote 是无序的。如果服务端修改了一个属性然后触发 Remote,客户端可能先看到其中任意一个。请监听变化本身,例如通过
GetPropertyChangedSignal,而不要假定它已经到达。 - 还没有处理函数。RemoteEvent 消息会排在队列中,直到处理函数连接。队列是有上限的:队列满了之后,后续消息会被丢弃,Output 中会出现
Remote event invocation discarded错误。 - 正在退出的玩家 会失去所有还没送到他那里的消息。
频率限制。根据 2026 年 9 月 30 日的文档,从客户端发往服务端的 RemoteEvent 和 UnreliableRemoteEvent 消息被限制在大约 每个客户端每秒 500 次请求。这个限制由同一类型的所有 Remote 共享,所以把一个繁忙的 Remote 拆成十个并不会提高它。超出限制后,RemoteEvent 消息会被推迟处理并保持顺序,而 UnreliableRemoteEvent 消息会被丢弃。引擎的限制完全挡不住一名玩家每秒调用你的 Remote 50 次,所以每个会修改东西的处理函数仍然需要自己的每名玩家限制。
RemoteEvent、RemoteFunction、UnreliableRemoteEvent 还是属性?
| 使用 | 用途 | 示例 | 注意事项 |
|---|---|---|---|
| RemoteEvent | 必须送达且按顺序到达的单向消息 | 客户端:“给这个零件上色”。服务端:“显示这条通知” | 在服务端检查每个参数 |
使用 InvokeServer 的 RemoteFunction | 客户端需要先得到答复才能继续 | 输入兑换码、确认购买 | 调用方会等待;每条路径都必须返回值 |
使用 InvokeClient 的 RemoteFunction | 几乎永远不用 | 改用 FireClient | 客户端出错、退出或不回答,都会让服务端的调用出错或卡住 |
| UnreliableRemoteEvent | 只有最后一次重要的频繁更新 | 瞄准方向、装饰性特效 | 消息会丢失或乱序;数据上限 1000 字节 |
| 由服务端设置的属性(attribute)或值对象 | 必须一直可见的共享状态,包括对后来进入的玩家 | 回合计时器、游戏阶段、门是否打开 | 只有服务端的修改会到达所有人;客户端通过 GetAttributeChangedSignal 或 Changed 监听 |
| BindableEvent | 同一侧脚本之间的通信 | 一个服务端脚本通知另一个回合已经结束 | 不会在服务端和客户端之间传递 |
要看 RemoteFunction 和检查在玩家付费的地方如何配合的完整示例,请阅读 如何做商店 GUI 教程。至于属性那一行,门的教程 中的服务端脚本在每扇门每次移动时都会设置它的 Open 属性,所以任何 LocalScript 都可以对它做出反应。
常见错误与解决办法
大多数 Remote 问题都能在 Output 窗口中看到(从 Window 菜单或 Script 选项卡打开)。先看那里,然后在下面找到你的症状。脚本错误教程 更详细地讲解了常见的错误信息。
Remote 的 WaitForChild 出现 Infinite yield possible
脚本在等待一个永远不会出现的 Remote。检查名字和大小写是否完全一致,以及 Remote 是否放在 ReplicatedStorage 中,而不是客户端看不到的 ServerStorage 或 ServerScriptService。
服务端收到的值不对,错位了一个
LocalScript 把玩家本身也传了过去,例如 remote:FireServer(player, 5)。Roblox 本来就会把发送者加为第一个参数,所以服务端看到的是 (player, player, 5)。请调用 remote:FireServer(5)。
调用 Remote 时什么都没发生
检查每个调用是否来自正确的一侧:FireServer 和 InvokeServer 只能在客户端代码中使用,FireClient、FireAllClients 和 InvokeClient 只能在服务端 Script 中使用。LocalScript 永远不会在 ServerScriptService、ServerStorage 或直接在 Workspace 中运行;请把它放在 StarterPlayerScripts、StarterGui、StarterCharacterScripts 或 StarterPack 中。然后在 Output 中查找处理函数内部的错误。
Remote event invocation discarded
消息到达了一个没有连接处理函数的 RemoteEvent,队列满了。通常是带处理函数的脚本在 :Connect 那一行之前就出错了、被禁用了,或者卡在等待某个永远不会加载的东西上。请把处理函数的连接放在脚本靠前的位置。
我这边能用,但其他玩家看不到变化
修改是在客户端做的,在 LocalScript 或 OnClientEvent 处理函数中。请在服务端的 OnServerEvent 处理函数中做修改。
InvokeServer 一直不返回
要么没有任何脚本设置 OnServerInvoke(Roblox 会把调用排在队列里,直到它被设置),要么回调卡在某个让出控制权的东西上,例如 WaitForChild 或数据存储请求。在回调的开头和结尾加上 print,看看它停在哪里。
用 RoCode 来做
RoCode 也可以直接在你打开的场景中把这些设置好。RoCode 是通过 Roblox Studio 插件工作的 AI 代理,所以它会在你的 Explorer 中创建 Remote 和脚本,而不是给你一段需要粘贴的代码。
让玩家点击就能给 Paintable 文件夹里的零件上色。使用 RemoteEvent,并把检查放在服务端:只允许这个文件夹里的零件,距离不超过 30 个 stud,每秒最多上色几次。
- 通常会先通过 Search Game 和 Search Scripts 浏览场景,查找现有的 Remotes 文件夹或处理函数,如果有就使用你的文件夹
- 通过 Create Instance 在 ReplicatedStorage 中创建 RemoteEvent,并通过 Create Script 编写服务端 Script 和 LocalScript
- 完成之前在 Studio 内通过 Check Script 检查每个脚本能否编译。这能发现编译错误,而不是逻辑错误:它不做类型检查,不运行 linter,也不执行你的代码
- 分批发送修改,每一批都是 Studio 历史记录中的一个撤销点
使用插件 3.9 或更新版本时,RoCode 可以运行一次简短的游戏测试并读取错误;使用插件 3.9.11 或更新版本时,它可以控制测试角色,但不会在 3D 窗口中点击零件。请自己点击 Play,试着破坏这些检查,例如从地图另一头给零件上色。如果出现错误,Check Output 可以读取你上一次游戏测试中的 Server 和 Client 行。大多数游戏系统都通过这样的 Remote 通信,所以当你 用 RoCode 一个系统一个系统地搭建游戏 时,还会再遇到它们。RoCode 如何连接 Studio。
常见问题
Roblox 中的 securing the client-server boundary 是什么意思?
这是 Roblox 文档中关于 Remote 安全的一个页面的名字,思路很简单:客户端通过 RemoteEvent 或 RemoteFunction 发送的一切都可能来自作弊者,所以服务端在采取行动之前要检查它。检查每个参数的类型,把数字限制在合理的范围内,检查玩家此刻是否被允许这样做,并限制每名玩家调用 Remote 的频率。上面的 检查清单 用代码展示了每一项。
RemoteFunction 安全吗?
InvokeServer 的安全程度取决于你的服务端回调:像对任何 RemoteEvent 一样检查它的参数并限制频率。有风险的方向是 InvokeClient,因为客户端出错、退出或一直不返回值,都会让服务端的调用出错或卡住。
作弊者能看到并调用我的 Remote 吗?
能。ReplicatedStorage 中的一切都会到达每个客户端,被修改过的客户端可以用任意参数调用任何 Remote。重命名或隐藏 Remote 并不能让它们变安全;让它们安全的是在服务端检查每个参数。
一个客户端能把 RemoteEvent 发给另一个客户端吗?
不能直接发送。先发送到服务端,在那里检查,然后使用 FireClient 或 FireAllClients。
RemoteEvent 可以多频繁地调用?
Roblox 文档给出的限制是,发往服务端的 RemoteEvent 和 UnreliableRemoteEvent 消息大约为每个客户端每秒 500 次请求,由同一类型的所有 Remote 共享。请保持在远低于这个数的水平,并给每个处理函数设置自己的每名玩家限制。
FireAllClients 能到达后来进入的玩家吗?
不能。它只到达此刻已连接的玩家。对于迟到的玩家也需要的状态,请在服务端设置属性或值对象。
RemoteEvent 和 BindableEvent 有什么区别?
RemoteEvent 在服务端和客户端之间传递。BindableEvent 连接同一侧的脚本,例如两个服务端脚本。
参考资料
- Roblox Creator Docs: Remote events and callbacks(英文). FireServer、FireClient、InvokeServer、InvokeClient 的风险、参数限制和送达保证
- Roblox Creator Docs: Securing the client-server boundary(英文). 检查的层级、NaN、频率限制、客户端之间的转发
- Roblox Creator Docs: Security and cheat mitigation tactics(英文). 被修改的客户端能做什么,以及服务端的权威
- Roblox Creator Docs: Network ownership, movement validation, and physics(英文). 为什么客户端控制自己的角色,以及距离检查的局限
- Roblox Engine API: RemoteEvent(英文). 频率限制和 invocation discarded 错误
- Roblox Engine API: RemoteFunction(英文). OnServerInvoke、关于 InvokeClient 的警告以及 streaming 的注意事项
- Roblox Engine API: UnreliableRemoteEvent(英文). 1000 字节的数据限制
- Roblox Creator Docs: Properties and attributes(英文). 属性变化与 remote events 之间的复制顺序
代码如何验证:本页的所有脚本都已用 Roblox API 类型定义(luau-lsp,2026年11月20日)通过 Luau strict 类型检查。类型检查能发现 API 名称写错和类型不匹配,但发现不了游戏逻辑上的错误。发布前请务必在 Studio 中测试。