MessagingService and TeleportService combined

Hey there, I really need help.

I want to make sure that a player is teleported using MessagingService. So the new instance sends a message on a specific and unique topic to the older instance to say that the player has been teleported successfully: he is in the new instance.

Here is the code:

--// OLDER INSTANCE //--

game.Players.PlayerRemoving:Connect(function() --This function is made to keep the server opened for a maximum of 20 seconds
    if #game.Players:GetPlayers() == 0 then
        game:BindToClose(function()
            local id = 0
            canClose = false

            repeat wait(1) id += 1
            until canClose == true or id >= 20
        end)
    end
end)

--Teleports a very specific player (that is considered as the "host" in multiplayer)
TeleportService:TeleportToPrivateServer(placeId, code, {Player}, "", "", game.ReplicatedFirst.teleportScreen)

local connection = nil
connection = MessagingService:SubscribeAsync(tostring(Id), function(message)
    if message.Data == "Done" 
        TeleportService:TeleportToPrivateServer(placeId,  code,game.Players:GetPlayers(), "", "", game.ReplicatedFirst.teleportScreen)
    end

    if worldSelection ~= nil then
        MessagingService:PublishAsync(Id.."_world", worldSelection) --This is not important in the script : it is used for a creative mode : it says which world has been selected
    end
                    
    canClose = true --Close the server instance faster

    connection:Disconnect()
end)
--// NEW INSTANCE //--

game.Players.PlayerAdded:Connect(function(Player)
    if Id == nil then
        Id = Player.UserId
        script.Parent:WaitForChild("Id").Value = Id
        
        MessagingService:PublishAsync(tostring(Id), "Done")
        
        print("Inter-server communication validation. Topic: '"..Id.."' , Message: 'Done'. Awaiting for further players.")
        
        script:WaitForChild("pauseMenu"):Clone().Parent = Player.PlayerGui
    end
end)

There must be a latency that makes the communication not working sometimes.
Because the thing is that, sometimes it works perfectly fine but sometimes not.

I tried to move the function in a different order but I saw that SubscribeAsync was a yielding function so I may keep it at the very end of the program to make it not yield important parts.

If you know how to fix this issue, or even a better way to do ; I would love to know what you have in mind !

1 Like

When it doesn’t work, does it consistently stop working? Or is it just randomly a few times? They write on messaging service that the messages may not always deliver. But this should probably happen not often at all.

It’s also possible that the subscription failed. You should wrap it in a pcall() to check if it’s a success or failure.

Well, it works sometimes but not all the time (and I would love it to work like that)