Aprenda
Classe do mecanismo
DataModel
Não criável

*Este conteúdo é traduzido por IA (Beta) e pode conter erros. Para ver a página em inglês, clique aqui.


Amostras de código
ObterServiço()
local Workspace = game:GetService("Workspace")
local Lighting = game:GetService("Lighting")
-- Exemplos de modificação de propriedades desses serviços
Workspace.Gravity = 20
Lighting.ClockTime = 4

Referência API
Propriedades
CreatorId
Somente leitura
Não replicado
Ler Parallel
DataModel.CreatorId:number
Amostras de código
Detectar quando o proprietário do lugar entra no jogo
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
if game.CreatorType == Enum.CreatorType.User then
if player.UserId == game.CreatorId then
print("O proprietário do lugar entrou no jogo!")
end
elseif game.CreatorType == Enum.CreatorType.Group then
if player:IsInGroupAsync(game.CreatorId) then
print("Um membro do grupo que possui o lugar entrou no jogo!")
end
end
end)

CreatorType
Somente leitura
Não replicado
Ler Parallel
DataModel.CreatorType:Enum.CreatorType
Amostras de código
Detectar quando o proprietário do lugar entra no jogo
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
if game.CreatorType == Enum.CreatorType.User then
if player.UserId == game.CreatorId then
print("O proprietário do lugar entrou no jogo!")
end
elseif game.CreatorType == Enum.CreatorType.Group then
if player:IsInGroupAsync(game.CreatorId) then
print("Um membro do grupo que possui o lugar entrou no jogo!")
end
end
end)

Environment
Somente leitura
Não replicado
Segurança do script Roblox
Ler Parallel
DataModel.Environment:string

GameId
Somente leitura
Não replicado
Ler Parallel
DataModel.GameId:number

GearGenreSetting
Obsoleto

Genre
Obsoleto

JobId
Somente leitura
Não replicado
Ler Parallel
DataModel.JobId:string

lighting
Obsoleto

MatchmakingType
Somente leitura
Não replicado
Ler Parallel
DataModel.MatchmakingType:Enum.MatchmakingType

PlaceId
Somente leitura
Não replicado
Ler Parallel
DataModel.PlaceId:number

PlaceVersion
Somente leitura
Não replicado
Ler Parallel
DataModel.PlaceVersion:number
Amostras de código
Número da versão do servidor GUI
local StarterGui = game:GetService("StarterGui")
local versionGui = Instance.new("ScreenGui")
local textLabel = Instance.new("TextLabel")
textLabel.Position = UDim2.new(1, -10, 1, 0)
textLabel.AnchorPoint = Vector2.new(1, 1)
textLabel.Size = UDim2.new(0, 150, 0, 40)
textLabel.BackgroundTransparency = 1
textLabel.TextColor3 = Color3.new(1, 1, 1)
textLabel.TextStrokeTransparency = 0
textLabel.TextXAlignment = Enum.TextXAlignment.Right
textLabel.TextScaled = true
local placeVersion = game.PlaceVersion
textLabel.Text = string.format("Versão do servidor: %s", placeVersion)
textLabel.Parent = versionGui
versionGui.Parent = StarterGui

PrivateServerId
Somente leitura
Não replicado
Ler Parallel
DataModel.PrivateServerId:string
Amostras de código
Detectando Servidores Privados
local function getServerType()
if game.PrivateServerId ~= "" then
if game.PrivateServerOwnerId ~= 0 then
return "VIPServer"
else
return "ReservedServer"
end
else
return "StandardServer"
end
end
print(getServerType())

PrivateServerOwnerId
Somente leitura
Não replicado
Ler Parallel
DataModel.PrivateServerOwnerId:number
Amostras de código
Detectando Servidores Privados
local function getServerType()
if game.PrivateServerId ~= "" then
if game.PrivateServerOwnerId ~= 0 then
return "VIPServer"
else
return "ReservedServer"
end
else
return "StandardServer"
end
end
print(getServerType())

RunService
Somente leitura
Não replicado
Ler Parallel
DataModel.RunService:RunService

VIPServerId
Obsoleto

VIPServerOwnerId
Obsoleto

Workspace
Somente leitura
Não replicado
Ler Parallel
DataModel.Workspace:Workspace

workspace
Obsoleto

Métodos
BindToClose
DataModel:BindToClose(function:function):()
Parâmetros
function:function
Devolução
()
Amostras de código
Salvando dados de jogador antes de desligar
local DataStoreService = game:GetService("DataStoreService")
local RunService = game:GetService("RunService")
local playerDataStore = DataStoreService:GetDataStore("PlayerData")
local allPlayerSessionDataCache = {}
local function savePlayerDataAsync(userId, data)
return playerDataStore:UpdateAsync(userId, function(oldData)
return data
end)
end
local function onServerShutdown(closeReason)
if RunService:IsStudio() then
-- Evitar gravar dados do estúdio em produção e atrasar o fechamento da sessão de teste
return
end
-- Referência para suspender e retomar mais tarde
local mainThread = coroutine.running()
-- Conta para cima para cada nova thread, para baixo quando a thread termina. Quando 0 é alcançado,
-- a thread individual sabe que é a última a terminar e deve retomar a thread principal
local numThreadsRunning = 0
-- Chamar esta função mais tarde inicia em uma nova thread por causa de coroutine.wrap
local startSaveThread = coroutine.wrap(function(userId, sessionData)
-- Realiza a operação de salvamento
local success, result = pcall(savePlayerDataAsync, userId, sessionData)
if not success then
-- Poderia implementar uma nova tentativa
warn(string.format("Falha ao salvar os dados de %d: %s", userId, result))
end
-- Thread finalizada, decrementar contador
numThreadsRunning -= 1
if numThreadsRunning == 0 then
-- Esta foi a última thread a terminar, retomar a thread principal
coroutine.resume(mainThread)
end
end)
-- Isso assume que playerData é limpo da tabela de dados durante um salvamento final em PlayerRemoving,
-- então isso está iterando sobre todos os dados dos jogadores ainda no jogo que não foram salvos
for userId, sessionData in pairs(allPlayerSessionDataCache) do
numThreadsRunning += 1
-- Este loop termina de rodar e contar numThreadsRunning antes que qualquer uma das
-- threads de salvamento comece, pois coroutine.wrap tem uma deferral embutida na inicialização
startSaveThread(userId, sessionData)
end
if numThreadsRunning > 0 then
-- Atrasar o desligamento até que as threads de salvamento terminem. Retomado pela última thread de salvamento quando termina
coroutine.yield()
end
end
game:BindToClose(onServerShutdown)
Ligando e Lidando com o Encerramento do Jogo
game:BindToClose(function(closeReason)
print(`Fechando com a razão {closeReason}`)
task.wait(3)
print("Feito")
end)

GetJobsInfo
Segurança do plugin
DataModel:GetJobsInfo():{any}
Devolução
Amostras de código
Obtendo Informações de Empregos
local jobInfo = game:GetJobsInfo()
local jobTitles = jobInfo[1]
table.remove(jobInfo, 1)
local divider = string.rep("-", 120)
print(divider)
warn("INFORMAÇÕES DO EMPREGO:")
print(divider)
for _, job in pairs(jobInfo) do
for jobIndex, jobValue in pairs(job) do
local jobTitle = jobTitles[jobIndex]
warn(jobTitle, "=", jobValue)
end
print(divider)
end

GetMessage
Obsoleto

GetObjects
Obsoleto

GetRemoteBuildMode
Obsoleto

IsGearTypeAllowed
Obsoleto

IsLoaded
DataModel:IsLoaded():boolean
Devolução
Amostras de código
Tela de Carregamento Personalizada
local Players = game:GetService("Players")
local ReplicatedFirst = game:GetService("ReplicatedFirst")
local player = Players.LocalPlayer
local playerGui = player:WaitForChild("PlayerGui")
-- Crie uma tela de carregamento básica
local screenGui = Instance.new("ScreenGui")
screenGui.IgnoreGuiInset = true
local textLabel = Instance.new("TextLabel")
textLabel.Size = UDim2.new(1, 0, 1, 0)
textLabel.BackgroundColor3 = Color3.fromRGB(0, 20, 40)
textLabel.Font = Enum.Font.GothamMedium
textLabel.TextColor3 = Color3.new(0.8, 0.8, 0.8)
textLabel.Text = "Carregando"
textLabel.TextSize = 28
textLabel.Parent = screenGui
-- Coloque toda a tela GUI no GUI do jogador
screenGui.Parent = playerGui
-- Remova a tela de carregamento padrão
ReplicatedFirst:RemoveDefaultLoadingScreen()
--task.wait(3) -- Opcionalmente, force a tela a aparecer por um número mínimo de segundos
if not game:IsLoaded() then
game.Loaded:Wait()
end
screenGui:Destroy()

SavePlace
Obsoleto

SetPlaceId
Segurança do plugin
DataModel:SetPlaceId(placeId:number):()
Parâmetros
placeId:number
Devolução
()

SetUniverseId
Segurança do plugin
DataModel:SetUniverseId(universeId:number):()
Parâmetros
universeId:number
Devolução
()

Eventos
AllowedGearTypeChanged
Obsoleto

GraphicsQualityChangeRequest
DataModel.GraphicsQualityChangeRequest(betterQuality:boolean):RBXScriptSignal
Parâmetros
betterQuality:boolean
Amostras de código
Lidando com Mudanças de Qualidade Gráfica pelo Usuário
game.GraphicsQualityChangeRequest:Connect(function(betterQuality)
if betterQuality then
print("O usuário solicitou um aumento na qualidade gráfica!")
else
print("O usuário solicitou uma diminuição na qualidade gráfica!")
end
end)

ItemChanged
Obsoleto

Loaded
DataModel.Loaded():RBXScriptSignal

ServerRestartScheduled
Recursos: ServerCommunication
DataModel.ServerRestartScheduled(
restartTime:DateTime, source:Enum.CloseReason, attributes:Dictionary
Parâmetros
restartTime:DateTime
attributes:Dictionary
Amostras de código
ReinicializaçãoDoServidorAgendada
local roundInProgress = false -- Definido em outro lugar no código do jogo sempre que uma rodada de jogo começa ou termina
local restartPending = false
game.ServerRestartScheduled:Connect(function(restartTime, source, attributes)
local msg = attributes and attributes.message or ""
local timeStr = restartTime:FormatLocalTime("LTS", "en-us") -- como isso é executado no servidor, estará em UTC
-- Encaminhe esses campos para os clientes via remote:FireAllClients() para exibir mensagens personalizadas na sua IU
print(string.format("Reinicialização do servidor em %s da fonte: %s. Razão: %s.", timeStr, tostring(source), msg))
if not roundInProgress then
print("Nenhuma rodada em andamento. Teletransportando jogadores em 10 segundos")
task.wait(10)
-- Teletransportar jogadores quando uma reinicialização foi agendada os trará para um servidor na versão mais recente do local
game:GetService("TeleportService"):TeleportAsync(game.PlaceId, game:GetService("Players"):GetPlayers())
else
-- Você pode adicionar código para teletransportar jogadores após o final de uma rodada de jogo se restartPending for verdadeiro.
restartPending = true
end
end)

Callbacks
OnClose
Obsoleto

©2026 Roblox Corporation, Roblox, o logotipo Roblox e Powering Imagination estão entre nossas marcas registradas e não registradas nos EUA e em outros países.