在副场景中创建一个私服,需要场景id,创建完的私人服务器会返回访问码,该访问码是唯一的,其他玩家想要进入同个服务器的副场景,都需要通过该访问码:
local function teleportChanged(this,id) --this是玩家表,id是场景id
local reservedServerAccessCode = TeleportService:ReserveServer(tonumber(id))
TeleportModule.teleportWithRetry(tonumber(id), reservedServerAccessCode, this,nil)
end
随后将需要传送的玩家放进添加进表(table)里,调用上方函数:
teleportChanged({player},场景ID)
总源代码:
local TeleportService = game:GetService("TeleportService")
local TeleportModule = {}
local RETRY_DELAY = 2
local MAX_WAIT = 10
function teleportWithRetry(targetPlaceID, reservedServerAccessCode,playersTable, spawnName, teleportOptions, customLoadingScreen)
local function doTeleport(playerTable)
local success, errorMessage = pcall(function()
return TeleportService:TeleportToPrivateServer(targetPlaceID, reservedServerAccessCode,playerTable, spawnName, teleportOptions, customLoadingScreen)
end)
if not success then
warn(errorMessage)
-- 在定义的延迟后重试传送
wait(RETRY_DELAY)
doTeleport()
end
end
TeleportService.TeleportInitFailed:Connect(function(player, teleportResult, errorMessage)
if teleportResult ~= Enum.TeleportResult.Success then
warn(errorMessage)
-- 在定义的延迟后重试传送
wait(RETRY_DELAY)
doTeleport({player})
end
end)
doTeleport(playersTable)
end
local function teleportChanged(this,id)
local reservedServerAccessCode = TeleportService:ReserveServer(tonumber(id))
teleportWithRetry(tonumber(id), reservedServerAccessCode, this,nil)
end
teleportChanged({player},场景ID)--调用函数
使用使直接调用“teleportChanged({player},场景ID)”就可以了。