重點摘要
RemoteEvent 是一種物件,通常放在 ReplicatedStorage,負責跨越用戶端與伺服器之間的界線傳送訊息。LocalScript 呼叫 FireServer,伺服器就會在 OnServerEvent 收到訊息,而且第一個參數會自動加上送出訊息的 Player。伺服器呼叫 FireClient(player, ...) 或 FireAllClients(...),LocalScript 就會在 OnClientEvent 收到訊息。
- 只有在用戶端需要答案時才使用 RemoteFunction(
InvokeServer與OnServerInvoke)。避免使用InvokeClient:發生錯誤、已經離開或永遠不回傳數值的用戶端,會讓伺服器上的呼叫壞掉。 - 絕對不要相信用戶端送來的任何東西。在伺服器上檢查每個參數的型別、範圍與歸屬、與玩家的距離,以及他呼叫 remote 的頻率。
- 函式、metatable,以及另一端看不到的物件,都無法在傳送後保留下來。UnreliableRemoteEvent 可能遺失訊息或打亂順序,而且會丟棄任何超過 1000 位元組的資料。
本頁內容
為什麼需要 RemoteEvent
每個 Roblox 遊戲都是一台伺服器,再加上每位玩家各一個用戶端。這裡由伺服器作主:新物件或屬性變更,只有由伺服器做出時才會傳到所有玩家那裡。在 LocalScript 做的變更只會留在一台裝置上,只有少數例外,例如玩家自己的角色,它的移動由該玩家的用戶端控制。因此,當點擊或按鍵需要改變共用的世界時,用戶端必須請求伺服器;而當伺服器希望某位玩家的畫面做出反應時,就必須通知那個用戶端。如果你還不熟悉 Script 與 LocalScript 的分工,請先閱讀 Script vs LocalScript vs ModuleScript(英文)。如果你剛開始寫 Script,請先看如何在 Roblox Studio 撰寫 Script。
為了跨越這條界線,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
這篇教學中的 Script 都透過 WaitForChild 找到 remote。如果 remote 已經在那裡,它會立刻回傳;如果還沒出現,它會等待,例如伺服器 Script 在遊戲進行中才建立 remote 的情況。每一種請求各建立一個 remote:這樣每個伺服器處理函式只需要檢查一種參數形式,要寫對比起一個 remote 包辦所有情況容易得多。
模式 1:用戶端到伺服器,並在伺服器上檢查
最常見的需求:玩家在自己的畫面上做了某件事,由伺服器決定會發生什麼。在這裡玩家按 Q 從四種顏色中選一種,再點擊或輕觸 part 替它上色。因為上色的是伺服器,所以每個人都看得到新顏色。
用戶端只送出兩樣東西:哪個 part,以及顏色的編號。它永遠不會送出顏色本身;同樣地,在其他遊戲中它也不應該送出價格、獎勵或傷害數值。修改過的用戶端可以送出任何東西,所以真正的資料(這裡是調色盤)由伺服器保存,而參數只被當成需要檢查的請求。
- 在 Workspace 中插入名為
Paintable的 Folder,並在裡面放幾個已固定(Anchored)的 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 -- 角色與 part 之間的 stud 數
local COOLDOWN_SECONDS = 0.25
local lastPaint: { [Player]: number } = {}
-- 第一個參數一定是呼叫 remote 的玩家。它由 Roblox 自動填入,
-- 所以可以信任。它之後的所有東西都來自用戶端,不能信任。
paintRequest.OnServerEvent:Connect(function(player: Player, part: unknown, colourIndex: unknown)
-- 1. 型別:真正的 part,而不是假裝成 part 的 table
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 資料夾中的 part,遊戲中的其他東西都不行
if not part:IsDescendantOf(paintable) then
return
end
-- 4. 距離:玩家的角色必須靠近 part
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 資料夾裡的 part
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 把畫面資料傳給這一位玩家,再由他的裝置移動攝影機。
這組 Script 會在玩家加入時顯示歡迎訊息。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 中你可能在這個 Script 連接之前就已經加入,所以也歡迎已經在場的每個人
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 已經能顯示它。
這個 Script 會在玩家第一次碰到終點線時向所有人宣布。在 Workspace 加入一個名為 FinishLine 的已固定 Part,再把 Script 加到 ServerScriptService。
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 只有一個伺服器回呼函式。如果有兩個 Script 替同一個 RemoteFunction 設定 OnServerInvoke,只有最後一個有效。
InvokeClient 為什麼危險
RemoteFunction 也可以反方向運作,在伺服器使用 InvokeClient,在用戶端使用 OnClientInvoke。Roblox 文件列出了三個嚴重風險:
- 如果用戶端的回呼函式發生錯誤,伺服器也會發生錯誤。
- 如果玩家在呼叫過程中離開,
InvokeClient會發生錯誤。 - 如果用戶端一直不回傳數值,伺服器 Script 會永遠等下去。
修改過的用戶端掌控自己的回呼函式,所以作弊者可以故意製造第三種情況,想卡住這條伺服器執行緒多久就多久。要更新玩家的畫面,請使用 FireClient。如果伺服器真的需要用戶端的資訊,就送出一個 RemoteEvent,讓用戶端透過另一個 RemoteEvent 回覆,並在伺服器上把沒有回覆視為正常情況。
在伺服器上檢查每一個參數
外掛作弊者可以用任何參數、任意次數呼叫任何 RemoteEvent 或 RemoteFunction。唯一無法偽造的是第一個參數:Roblox 會自己填入送出訊息的 Player。之後的所有東西,都必須在伺服器行動之前檢查過。把 remote 藏起來或在 LocalScript 中檢查都沒有用,因為作弊者掌控自己的用戶端。
| 檢查 | 伺服器要問的問題 | 範例 |
|---|---|---|
| 型別 | 這是我預期的型別嗎?是 Instance,而不是刻意組成看起來像 Instance 的 table? | typeof(part) == "Instance" and part:IsA("BasePart") |
| 範圍 | 數字是有限值,而且在允許的範圍內嗎?文字長度合理嗎? | math.isfinite(n)、n >= 1 and n <= 4、#text <= 20 |
| 歸屬 | 這位玩家擁有這個物品、錢夠用,或有權對這個物件採取行動嗎? | 物品在他的背包裡;part 位於 Paintable 裡面 |
| 距離 | 在伺服器那份世界中,玩家的角色夠近嗎?替延遲留一點餘裕。 | 距離 part 不超過 30 stud |
| 頻率 | 這位玩家是不是送得太頻繁了? | 每位玩家的冷卻時間,或可累積呼叫次數的限制 |
NaN 值得特別提醒。它是數字,所以 type(x) == "number" 會通過,但任何與它的比較都會得到 false,像 x < 0 or x > 100 這樣的檢查會讓它直接通過。math.isfinite(x) 會拒絕 NaN 與正負無限大。
請記得距離檢查的極限。每個用戶端都掌控自己角色的物理,所以外掛作弊者可以在呼叫前把角色移到目標旁邊。這項檢查仍然能擋下最簡單的濫用,也就是站在原地對整張地圖動手。目標 part 請保持固定(Anchored):Roblox 安全文件提到,外掛作弊者可以取得自己附近未固定 part 的網路所有權,把它們拉近,這樣就能繞過距離檢查。
以下是把同樣的檢查寫成 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
-- 有長度限制的文字。utf8.len 對無效的 UTF-8 會回傳 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 的 table 無法通過 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)
限制器會在玩家離開時刪除他的紀錄,所以它的 table 不會在伺服器整個生命週期中一直變大。
在武器中這些檢查最重要:絕對不要讓用戶端回報打中了誰。劍的教學中的 remote 完全不帶參數,由伺服器自己找出目標。槍枝教學只送出瞄準點,伺服器先檢查它的型別、NaN 與距離,再發射自己的射線。
選單也遵守同樣的規則:送出選擇,而不是結果。在 NPC 對話教學中,用戶端只送出按下的按鈕編號,伺服器自己查這個回答會帶來什麼。傳送教學中的選單送出的是地點名稱而不是位置,伺服器在自己的資料夾中找到地點,並檢查需要多少 Wins。
可以傳送與不能傳送的東西
可以傳送數字、字串、布林值、Roblox 型別(例如 Vector3、CFrame、Color3 與 Enum 項目)、雙方都看得到的 Instance,以及由這些東西組成的 table。有些值在傳送途中會改變或消失:
| 你送出 | 會發生什麼 |
|---|---|
| 函式 | 另一端收到 nil |
| 帶有 metatable 的 table | metatable 會遺失,連同 table 只透過它才有的一切 |
| 混合數字鍵與字串鍵的 table | Roblox 建議不要這樣做:請送出純陣列或純字典 |
內含 nil 值的 table | 請避免:Roblox 不建議在任何索引放 nil |
| 以 Instance、userdata 或 function 為鍵的 table | 這些鍵會變成字串 |
| 接收方看不到的 Instance,例如來自 ServerStorage 或在 LocalScript 中建立的 | 另一端收到 nil |
| 任何 table | 接收方收到的是副本,而不是同一個 table |
好習慣:送出識別碼,而不是物件或數值。物品名稱、選項編號、伺服器可以找到並檢查的 part。接下來由伺服器使用自己的資料處理。
為什麼 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 時,伺服器剛建立的 part 可能在函式回傳時還沒傳到用戶端。 - 回呼函式被另一個 Script 設定了。只有最後一次指定的
OnServerInvoke有效。在你的 Script 中搜尋這個 remote 的名稱。
如果呼叫完全沒有回傳,代表還沒有任何 Script 設定 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 還是 attribute?
| 使用 | 用途 | 範例 | 要注意的地方 |
|---|---|---|---|
| RemoteEvent | 必須送達且依序抵達的單向訊息 | 用戶端:「替這個 part 上色」。伺服器:「顯示這則通知」 | 在伺服器上檢查每一個參數 |
使用 InvokeServer 的 RemoteFunction | 用戶端需要答案才能繼續 | 輸入兌換碼、確認購買 | 呼叫方會等待;每條路徑都必須回傳數值 |
使用 InvokeClient 的 RemoteFunction | 幾乎永遠不要 | 改用 FireClient | 發生錯誤、已經離開或沒有回應的用戶端,會讓伺服器上的呼叫壞掉或卡住 |
| UnreliableRemoteEvent | 頻繁的更新,只有最新的值重要 | 瞄準方向、裝飾特效 | 訊息會遺失或打亂順序;資料上限 1000 位元組 |
| 由伺服器設定的 attribute 或 value 物件 | 必須隨時看得到的共用狀態,包括較晚加入的玩家 | 回合計時器、遊戲階段、門是否打開 | 只有伺服器的變更會傳到所有人;用戶端透過 GetAttributeChangedSignal 或 Changed 監聽 |
| BindableEvent | 同一端 Script 之間的溝通 | 一個伺服器 Script 通知另一個回合已經結束 | 不會跨越伺服器與用戶端 |
想看 RemoteFunction 與檢查在玩家付費的地方如何一起運作的完整範例,請參考如何製作商店 GUI教學。至於 attribute 那一列,門的教學中的伺服器 Script 會在每扇門每次移動時設定 Open 屬性,任何 LocalScript 都能對它做出反應。
常見錯誤與解法
大部分 remote 的問題都能在 Output 視窗中看到(從 Window 選單或 Script 分頁打開)。先看那裡,再在下方找到你的症狀。Script 錯誤教學會更詳細地說明常見的錯誤訊息。
remote 的 WaitForChild 出現 Infinite yield possible
Script 在等一個永遠不會出現的 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,佇列因此滿了。通常是帶有處理函式的 Script 在 :Connect 那一行之前就出錯、被停用,或卡在等待一個永遠不會載入的東西。請把處理函式連接得更靠近 Script 的開頭。
我這邊可以,但其他玩家看不到變更
變更是在用戶端做的,在 LocalScript 或 OnClientEvent 處理函式中。請改在伺服器的 OnServerEvent 處理函式中進行。
InvokeServer 永遠不回傳
要不是沒有任何 Script 設定 OnServerInvoke(Roblox 會把呼叫排進佇列,直到設定為止),就是回呼函式卡在會讓出控制權的東西上,例如 WaitForChild 或資料儲存區的請求。在回呼函式的開頭與結尾加上 print,就能看出它停在哪裡。
用 RoCode 完成
RoCode 也能直接在你開啟的場景中設定好這一切。RoCode 是透過 Roblox Studio 外掛程式運作的 AI 代理,所以它會在你的 Explorer 中建立 remote 與 Script,而不是丟給你一段需要自己貼上的程式碼。
讓玩家點擊就能替 Paintable 資料夾中的 part 上色。使用 RemoteEvent,並把檢查留在伺服器上:只限這個資料夾的 part、距離不超過 30 stud,每秒最多上色幾次。
- 通常會先透過 Search Game 與 Search Scripts 瀏覽場景,尋找現成的 Remotes 資料夾或處理函式,如果有就使用你的資料夾
- 透過 Create Instance 在 ReplicatedStorage 建立 RemoteEvent,並透過 Create Script 撰寫伺服器 Script 與 LocalScript
- 完成前會在 Studio 內透過 Check Script 檢查每個 Script 能否編譯。這能抓到編譯錯誤,而不是邏輯錯誤:它不做型別檢查、不執行 linter,也不會執行你的程式碼
- 分批送出變更,每一批都是 Studio 歷史紀錄中的一個復原點
使用 3.9 或更新版本的外掛程式時,RoCode 可以執行簡短的試玩測試並讀取錯誤;使用 3.9.11 或更新版本時,它可以操控測試角色,但它不會在 3D 視窗中點擊 part。請自己按 Play,試著破解這些檢查,例如從地圖另一端替 part 上色。如果出現錯誤,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 會送到較晚加入的玩家嗎?
不會。它只送到當下已連線的玩家。晚到的玩家需要的狀態,請在伺服器上設定 attribute 或 value 物件。
RemoteEvent 和 BindableEvent 有什麼不同?
RemoteEvent 會在伺服器與用戶端之間傳遞。BindableEvent 連接同一端的 Script,例如兩個伺服器 Script。
來源與延伸閱讀
- 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 之間的複寫順序
程式碼如何驗證:本頁每一段 Script 都通過 Luau 嚴格型別檢查,並使用 Roblox API 定義(luau-lsp,2026年11月20日)。型別檢查能找出拼錯的 API 與錯誤的型別,但無法檢查遊戲邏輯,所以發布前請先在 Studio 中測試。