跨伺服器訊息傳遞

*此內容是使用 AI(Beta 測試版)翻譯,可能含有錯誤。若要以英文檢視此頁面,請按一下這裡

通常,遊戲中的程式碼只能影響其運行所在的伺服器或客戶端,但在某些情況下,您可能希望不同的伺服器彼此通信,包括:

  • 全球公告 — 向所有遊戲伺服器發送公告,例如「有用戶發現了特殊物品!」。
  • 即時伺服器瀏覽器 — 編譯所有遊戲伺服器及其內部玩家的清單(每分鐘更新一次),並在最多 20 個伺服器上顯示此清單。

您可以使用 MessagingService 在遊戲中支援跨伺服器訊息傳遞。在您實作之前,您也可以使用 Teleportation Playground 範例遊戲來查看跨伺服器訊息傳遞的運作方式。最後,請參見 這裡 探索使用外部工具進行跨伺服器通信。

跨伺服器訊息傳遞設置

要啟用跨伺服器訊息傳遞,您必須設置一個 主題,這是一個可從多個伺服器訪問的自定義訊息頻道。在您創建主題後,您可以 訂閱用戶 到該主題以接收訊息,並啟用 發佈訊息 到該主題。

訂閱用戶以接收訊息

使用 MessagingService:SubscribeAsync() 訂閱用戶到一個主題,並指定一個回調函數以檢測發布到該主題的訊息。例如,以下代碼示例訂閱所有用戶到一個 FriendServerEvent 主題,當任何用戶被傳送到不同伺服器時接收訊息。


local MessagingService = game:GetService("MessagingService")
local Players = game:GetService("Players")
local MESSAGING_TOPIC = "FriendServerEvent"
Players.PlayerAdded:Connect(function(player)
-- 訂閱主題
local subscribeSuccess, subscribeConnection = pcall(function()
return MessagingService:SubscribeAsync(MESSAGING_TOPIC, function(message)
print(message.Data)
end)
end)
if subscribeSuccess then
-- 當玩家族譜變更時取消訂閱主題
player.AncestryChanged:Connect(function()
subscribeConnection:Disconnect()
end)
end
end)

發佈訊息

使用 MessagingService:PublishAsync() 匹配特定主題並將訊息發佈到該主題。例如,以下代碼示例使用 MessagingService:PublishAsync() 通知所有用戶當一名用戶加入新伺服器時,包括代表用戶顯示名稱的 Player.Name 和唯一標識運行遊戲伺服器實例的 JobId


local MessagingService = game:GetService("MessagingService")
local Players = game:GetService("Players")
local MESSAGING_TOPIC = "FriendServerEvent"
Players.PlayerAdded:Connect(function(player)
-- 發佈到主題
local publishSuccess, publishResult = pcall(function()
local message = player.Name .. " 加入了 'JobId' 為 " .. game.JobId 的伺服器
MessagingService:PublishAsync(MESSAGING_TOPIC, message)
end)
if not publishSuccess then
print(publishResult)
end
end)
©2026 Roblox Corporation、Roblox、Roblox 標誌及 Powering Imagination 是我們在美國及其他國家地區的部分註冊與未註冊商標。