Aprender
Clase de motor
DataModel
No creable

*Este contenido se traduce usando la IA (Beta) y puede contener errores. Para ver esta página en inglés, haz clic en aquí.


Muestras de código
ObtenerServicio()
local Workspace = game:GetService("Workspace")
local Lighting = game:GetService("Lighting")
-- Ejemplos de modificar propiedades de estos servicios
Workspace.Gravity = 20
Lighting.ClockTime = 4

Referencia API
Propiedades
CreatorId
Solo lectura
No replicado
Leer paralelo
DataModel.CreatorId:number
Muestras de código
Detectar cuando el propietario del lugar se une al juego
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
if game.CreatorType == Enum.CreatorType.User then
if player.UserId == game.CreatorId then
print("¡El propietario del lugar se ha unido al juego!")
end
elseif game.CreatorType == Enum.CreatorType.Group then
if player:IsInGroupAsync(game.CreatorId) then
print("¡Un miembro del grupo que posee el lugar se ha unido al juego!")
end
end
end)

CreatorType
Solo lectura
No replicado
Leer paralelo
DataModel.CreatorType:Enum.CreatorType
Muestras de código
Detectar cuando el propietario del lugar se une al juego
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
if game.CreatorType == Enum.CreatorType.User then
if player.UserId == game.CreatorId then
print("¡El propietario del lugar se ha unido al juego!")
end
elseif game.CreatorType == Enum.CreatorType.Group then
if player:IsInGroupAsync(game.CreatorId) then
print("¡Un miembro del grupo que posee el lugar se ha unido al juego!")
end
end
end)

Environment
Solo lectura
No replicado
Seguridad de scripts Roblox
Leer paralelo
DataModel.Environment:string

GameId
Solo lectura
No replicado
Leer paralelo
DataModel.GameId:number

GearGenreSetting
Obsoleto

Genre
Obsoleto

JobId
Solo lectura
No replicado
Leer paralelo
DataModel.JobId:string

lighting
Obsoleto

MatchmakingType
Solo lectura
No replicado
Leer paralelo
DataModel.MatchmakingType:Enum.MatchmakingType

PlaceId
Solo lectura
No replicado
Leer paralelo
DataModel.PlaceId:number

PlaceVersion
Solo lectura
No replicado
Leer paralelo
DataModel.PlaceVersion:number
Muestras de código
Número de versión del 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("Versión del servidor: %s", placeVersion)
textLabel.Parent = versionGui
versionGui.Parent = StarterGui

PrivateServerId
Solo lectura
No replicado
Leer paralelo
DataModel.PrivateServerId:string
Muestras 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
Solo lectura
No replicado
Leer paralelo
DataModel.PrivateServerOwnerId:number
Muestras 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
Solo lectura
No replicado
Leer paralelo
DataModel.RunService:RunService

VIPServerId
Obsoleto

VIPServerOwnerId
Obsoleto

Workspace
Solo lectura
No replicado
Leer paralelo
DataModel.Workspace:Workspace

workspace
Obsoleto

Métodos
BindToClose
DataModel:BindToClose(function:function):()
Parámetros
function:function
Devuelve
()
Muestras de código
Guardando datos del jugador antes de apagar
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 escribir datos de estudio en producción y detener el cierre de sesión de prueba
return
end
-- Referencia para suspender y reanudar más tarde
local mainThread = coroutine.running()
-- Cuenta hacia arriba por cada nuevo hilo, hacia abajo cuando el hilo termina. Cuando se llega a 0,
-- el hilo individual sabe que es el último hilo en terminar y debería reanudar el hilo principal
local numThreadsRunning = 0
-- Llamar a esta función más tarde comienza en un nuevo hilo debido a coroutine.wrap
local startSaveThread = coroutine.wrap(function(userId, sessionData)
-- Realizar la operación de guardado
local success, result = pcall(savePlayerDataAsync, userId, sessionData)
if not success then
-- Se podría implementar un reintento
warn(string.format("Error al guardar los datos de %d: %s", userId, result))
end
-- Hilo terminado, decrementar contador
numThreadsRunning -= 1
if numThreadsRunning == 0 then
-- Este fue el último hilo en terminar, reanudar hilo principal
coroutine.resume(mainThread)
end
end)
-- Esto asume que playerData se limpia de la tabla de datos durante un guardado final en PlayerRemoving,
-- así que esto itera sobre todos los datos de los jugadores que todavía están en el juego y que no se han guardado
for userId, sessionData in pairs(allPlayerSessionDataCache) do
numThreadsRunning += 1
-- Este bucle termina de ejecutarse y contar numThreadsRunning antes de que cualquiera de
-- los hilos de guardado comience porque coroutine.wrap tiene una postergación incorporada al inicio
startSaveThread(userId, sessionData)
end
if numThreadsRunning > 0 then
-- Detener el apagado hasta que los hilos de guardado terminen. Reanudado por el último hilo de guardado cuando termina
coroutine.yield()
end
end
game:BindToClose(onServerShutdown)
Vinculación y Manejo del Cierre del Juego
game:BindToClose(function(closeReason)
print(`Cerrando con razón {closeReason}`)
task.wait(3)
print("Hecho")
end)

GetJobsInfo
Seguridad del plugin
DataModel:GetJobsInfo():{any}
Devuelve
Muestras de código
Obtener información de trabajos
local jobInfo = game:GetJobsInfo()
local jobTitles = jobInfo[1]
table.remove(jobInfo, 1)
local divider = string.rep("-", 120)
print(divider)
warn("INFORMACIÓN DE TRABAJOS:")
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
Devuelve
Muestras de código
Pantalla de Carga Personalizada
local Players = game:GetService("Players")
local ReplicatedFirst = game:GetService("ReplicatedFirst")
local player = Players.LocalPlayer
local playerGui = player:WaitForChild("PlayerGui")
-- Crea una pantalla de carga 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 = "Cargando"
textLabel.TextSize = 28
textLabel.Parent = screenGui
-- Asigna toda la pantalla GUI al GUI del jugador
screenGui.Parent = playerGui
-- Elimina la pantalla de carga predeterminada
ReplicatedFirst:RemoveDefaultLoadingScreen()
--task.wait(3) -- Opcionalmente fuerza a que la pantalla aparezca durante un número mínimo de segundos
if not game:IsLoaded() then
game.Loaded:Wait()
end
screenGui:Destroy()

SavePlace
Obsoleto

SetPlaceId
Seguridad del plugin
DataModel:SetPlaceId(placeId:number):()
Parámetros
placeId:number
Devuelve
()

SetUniverseId
Seguridad del plugin
DataModel:SetUniverseId(universeId:number):()
Parámetros
universeId:number
Devuelve
()

Eventos
AllowedGearTypeChanged
Obsoleto

GraphicsQualityChangeRequest
DataModel.GraphicsQualityChangeRequest(betterQuality:boolean):RBXScriptSignal
Parámetros
betterQuality:boolean
Muestras de código
Manejo de Cambios de Usuario en la Calidad Gráfica
game.GraphicsQualityChangeRequest:Connect(function(betterQuality)
if betterQuality then
print("¡El usuario ha solicitado un aumento en la calidad gráfica!")
else
print("¡El usuario ha solicitado una disminución en la calidad gráfica!")
end
end)

ItemChanged
Obsoleto

Loaded
DataModel.Loaded():RBXScriptSignal

ServerRestartScheduled
Capacidades: ServerCommunication
DataModel.ServerRestartScheduled(
restartTime:DateTime, source:Enum.CloseReason, attributes:Dictionary
Parámetros
restartTime:DateTime
attributes:Dictionary
Muestras de código
ReinicioDelServidorProgramado
local roundInProgress = false -- Establecer en otro lugar en el código del juego cada vez que una ronda de juego comienza o 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") -- dado que esto se ejecuta en el servidor, estará en UTC
-- Reenvía estos campos a los clientes vía remote:FireAllClients() para mostrar mensajes personalizados en tu UI
print(string.format("Reinicio del servidor a %s desde la fuente: %s. Razón: %s.", timeStr, tostring(source), msg))
if not roundInProgress then
print("No hay ronda en progreso. Teletransportando jugadores en 10 segundos")
task.wait(10)
-- Teletransportar a los jugadores cuando un reinicio ha sido programado los llevará a un servidor en la última versión del lugar
game:GetService("TeleportService"):TeleportAsync(game.PlaceId, game:GetService("Players"):GetPlayers())
else
-- Puedes agregar código para teletransportar a los jugadores después de que una ronda de juego termine si restartPending es verdadero.
restartPending = true
end
end)

Llamadas
OnClose
Obsoleto

©2026 Roblox Corporation. Roblox, el logotipo de Roblox y "Powering Imagination" son algunas de nuestras marcas registradas y no registradas en los Estados Unidos y otros países.