通常來說,體驗內的代碼只能影響它運行的伺服器或客戶端,但可能有情況需要不同的伺服器之間相互通訊,包括:
- 全球公告 — 向所有體驗服務器發送公告,例如「使用者找到了一件特殊道具!」
- 實時伺服器瀏覽器 — 編譯出所有經體驗伺服器的列表和誰在其中(每分鐘更新一次),並在最多 20 個伺服器上顯示列表。
您可以使用 MessagingService 在體驗中支持跨服務器傳訊。您也可以使用 傳送遊戲場 樣本體驗來看看跨伺服器訊息傳輸如何工作,在執行之前就可以確認它的功能。最後,請參閱這裡探索使用外部工具來探索跨服務器通信。
跨伺服器訊息傳送設定
若要啟用跨伺服器傳訊,您必須設定一個 主題 ,這是一個可從多個伺服器存取的自訂訊息通道。創建主題後,您可以訂閱用戶以接收訊息,並啟用發布訊息到主題。
訂閱使用者以收到訊息
使用 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() 來匹配特定主題並向其發布消息。例如,下列代碼示例使用 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 .. " joined server with 'JobId' of " .. game.JobId
MessagingService:PublishAsync(MESSAGING_TOPIC, message)
end)
if not publishSuccess then
print(publishResult)
end
end)