通常,体验中的代码只能影响运行在其上的服务器或客户端,但也许有情况需要不同的服务器之间相互通信,例如:
- 全球公告 — 向所有体验服务器发送公告,例如“用户发现了特殊物品!”
- 实时服务器浏览器 — 编译出所有体验服务器的列表以及谁在其中(每分钟更新一次)并在最多 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)