I would probably use datastoreservice to save information about certain worlds and their status and then save the access code for later use.
My server script would look something like this.
local teleportservice = game:GetService("TeleportService")
local players = game:GetService("Players")
local savedData = { ["Code"] = { isActive = false, accessCode = nil } } -- this is example data saved in the datastore
local placeid = game.PlaceId
local remoteEvent: RemoteEvent
function teleportToWorld(player, code)
local worldInfo = savedData[code]
local accessCode = worldInfo.accessCode
if (not worldInfo.isActive) then
accessCode = teleportservice:ReserveServer(placeid)
worldInfo.accessCode = accessCode -- update datastore too
end
teleportservice:TeleportToPrivateServer(placeid, accessCode, {player})
end
remoteEvent.OnServerEvent:Connect(teleportToWorld)
and then the local script will just fire that remote with the code to teleport to it.
In the reserved servers you could probably add a script that uses game:BindToClose() to set the active status of the server to false and remove the old access code