local
Players =
game:GetService("Players")
local
TeleportService =
game:GetService("TeleportService")
local
TARGET_PLACE_ID =
1234
-- replace with your own place ID
local
playerToTeleport = Players:GetPlayers()[1]
-- get the first user in the experience
TeleportService:TeleportAsync(TARGET_PLACE_ID, , teleportOptions)
Ви можете тільки зв'язатися з TeleportAsync() від серверів-підписів. Це обмеження скорочується клінікою-сидією вирощування. Якщо необхідно, ви можете скористатися Teleport() від клієнт-side scripts, але TeleportAsync() is recommended method.
Якщо ви збираєтеся дізнатися, що handling errors, коли встановлюють телепортацію, статтю Handling Failed Teleports .
Enabling Cross Experience Teleportation
Для надійності, телепортування користувача з вашого досвіду до іншого досвіду власне за іншими, або за іншими способами подалі, нескінченні. Досягти крос-експериментного телепортування, Open Game Settings > Security and enable Allow Third Party Teleports on Studio.
Creating Custom Teleport Screens
Якщо користувачі triggers teleport, вони кажуть про стандарт Roblox loading screen as they wait for the new place to load in. Ви можете отримати custom teleport screen to improve immersion for users calling TeleportService:SetTeleportGui() on the client and pass through the ScreenGui use before teleporting the user.Протягом докладного набору номерів customized ScreenGui located in ReplicatedStorage як loading screen when a teleport happens. It doesn't run any scripts inside of the ScreenGui .
local
TeleportService =
game:GetService("TeleportService")
local
ReplicatedStorage =
game:GetService("ReplicatedStorage")
local
teleportGui = ReplicatedStorage.TeleportGui
TeleportService:SetTeleportGui(teleportGui)
Customizing Teleport Options
Ви можете customize teleportations, так як teleporting users на конкретний сервер і повідомити user data along with teleports , за допомогою TeleportOptions instance and passing it to the TeleportService:TeleportAsync() метод.
Teleporting to Specific Servers
Для телепортів користувачів до конкретних серверів, натисніть на target server за допомогою TeleportOptions and pass it до TeleportService:TeleportAsync() метод. Якщо ви не вважаєте особливим сервером, користувачі можуть бути телепортовані в matchmade public server. Інформація про першого користувача в аркуші міститься в матчі, щоб public server.
Для телевізійних користувачів на конкретний public server, набір TeleportOptions.ServerInstanceId property as valid instance ID, which is unique identifier for public server.
local
teleportOptions = Instance.new("TeleportOptions")
teleportOptions.ServerInstanceId = targetServerId
Для телевізійних користувачів на конкретний ресурсний сервер, налаштований правильний TeleportOptions.
local
teleportOptions = Instance.new("TeleportOptions")
teleportOptions.ReservedServerAccessCode = reservedServerCode
Щоб отримати доступ до телепорту користувачів до нового сервісного сервера, встановити TeleportOptions.ShouldReserveServer на true.
local
teleportOptions = Instance.new("TeleportOptions")
teleportOptions.ShouldReserveServer =
true
Sending User Data Along with Teleports
Teleporting a user між places discards any local data поєднана з that user.Ви можете використовувати такі підходи до handle data persistence between places.
Якщо ви використовуєте простий user data як в-експеріоне currency or inventory, implemente data stores or memory stores to maintain data from place to place.
Для того, щоб мати основний неправильний формат даних від місця до місця, call TeleportOptions:SetTeleportData() перед passing it to TeleportAsync() .
Дозволяє pass secure data, використовуючи TeleportOptions:SetTeleportData() тому, що він є ризиком exploitation.
local
teleportData =
randomNumber = RNG:NextInteger(1,
100),
>
local
teleportOptions = Instance.new("TeleportOptions")
teleportOptions:SetTeleportData(teleportData)
Для того, щоб отримати всі дані користувача, які надходять від телепорту на сервері, використовуйте Player:GetJoinData() функція, яка відкликає до пункту включення даних, що поєднані з користувачем.
local
Players =
game:GetService("Players")
local
function
onPlayerAdded(player)
local
joinData = player:GetJoinData()
local
teleportData = joinData.TeleportData
local
randomNumber = teleportData.randomNumber
print(player.Name ..
"joined with the number"
.. randomNumber)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Щоб скористатися лише телепортом даних на клієнті, ви можете використовувати TeleportService:GetLocalPlayerTeleportData() .
Handling Failed Teleports
Як API повідомила, що потрібна мережа запитів, телепортів глибокої шкоди і невдачі. Хоча якщо випадок проходить і телепорт ініціатів, він може залишатися нестерпним в останній момент без повідомлень про помилку і тримає користувача на сервері. When this happens, it triggers TeleportService.TeleportInitFailed .
Wrap teleports in protected call ( pcall() ) and retry if it fails. Наступні приклади ModuleScript defines SafeTeleport функція до телепорту користувача в захисті повідомлень і handleFailedTeleport функція до відновлення виконаних телепортів, що є один-три рази і стрілки в valides ones, які мають помилки в коді.
local
TeleportService =
game:GetService("TeleportService")
local
ATTEMPT_LIMIT =
5
local
RETRY_DELAY =
1
local
FLOOD_DELAY =
15
local
function
SafeTeleport(placeId, players, options)
local
attemptIndex =
0
local
success, result
-- define pcall results outside of loop so results can be reported later on
repeat
success, result =
pcall(function()
return
TeleportService:TeleportAsync(placeId, players, options)
-- teleport the user in a protected call to prevent erroring
end)
attemptIndex +=
1
if
not
success
then
task.wait(RETRY_DELAY)
end
until
success
or
attemptIndex == ATTEMPT_LIMIT
-- stop trying to teleport if call був successful, чи if retry limit буде been reached
if
not
success
then
warn(result)
-- print the failure reason to output
end
return
success, result
end
local
function
handleFailedTeleport(player, teleportResult, errorMessage, targetPlaceId, teleportOptions)
if
teleportResult ==
Enum.TeleportResult.Flooded
then
task.wait(FLOOD_DELAY)
elseif
teleportResult ==
Enum.TeleportResult.Failure
then
task.wait(RETRY_DELAY)
else
- Якщо телепорт не вдається, повідомлення про помилку повертається
error(("Invalid teleport [%s]: %s"):format(teleportResult.Name, errorMessage))
end
SafeTeleport(targetPlaceId, , teleportOptions)
end
TeleportService.TeleportInitFailed:Connect(handleFailedTeleport)
return
SafeTeleport
Функції SafeTeleport receives the same arguments as the TeleportAsync() function. Ви можете використовувати наступні МодулиScript з функцією SafeTeleport для виконання телепортів з будь-якого часу в вашому дослідженні до зменшення можливих телепортів.
local
Players =
game:GetService("Players")
local
ServerScriptService =
game:GetService("ServerScriptService")
local
SafeTeleport =
require(ServerScriptService.SafeTeleport)
local
TARGET_PLACE_ID =
1818
-- replace with your own place ID
local
playerToTeleport = Players:GetPlayers()[1]
-- get the first user in the game
SafeTeleport(TARGET_PLACE_ID, , teleportOptions)
Як зробити кнопку в роблокс студіо, якщо при натисканні на неї, тебе телепортує в інший плейс
Щоб створити кнопку Roblox Studio, яка при натисканні телепортує гравця в інший плейс без використання ClickDetector, можна використовувати інтерфейсну кнопку (GUI Button). Ось необхідні кроки:
1. Створення кнопки у GUI:
1. Відкрийте Roblox Studio та завантажте ваш проект.
2. Перейдіть до вікна Explorer і знайдіть об'єкт StarterGui.
3. Зробіть правий клік на StarterGui та виберіть Insert Object → ScreenGui.
4. Всередині ScreenGui зробіть правий клік і виберіть Insert Object → TextButton.
2. Налаштування кнопки:
1. Виберіть TextButton у списку об'єктів.
2. У вікні Properties можна змінити текст кнопки, розмір, позицію та інші параметри.
3. Додавання скрипта для телепортації:
1. Зробіть правий клік на TextButton та виберіть Insert Object → LocalScript.
2. Вставте наступний код у створений скрипт:
local button = script.Parent
local placeId = YOUR_PLACE_ID -- Замініть YOUR_PLACE_ID на ID плейсу, куди хочете телепортувати
button.MouseButton1Click:Connect(function()
local TeleportService = гра: GetService("TeleportService")
local player = game.Players.LocalPlayer
TeleportService:Teleport(placeId, player)
end)
3. Замініть YOUR_PLACE_ID на ID вашого цільового плейсу.
Після виконання цих кроків, у вас буде GUI кнопка, яка при натисканні телепортуватиме гравця у вказаний плейс. (GPT)