数据模型(通常被称为后全球变量用于访问它)是Roblox的父子层次结构的根。其直接子女是服务,例如 Workspace 和 Lighting , 它们是 Roblox 游戏的基础组件。
代码示例
Demonstrates using game, the root instance of DataModel, to get services such as Workspace and Lighting.
local Workspace = game:GetService("Workspace")
local Lighting = game:GetService("Lighting")
-- Examples of modifying properties of these services
Workspace.Gravity = 20
Lighting.ClockTime = 4
概要
属性
描述拥有场景点的用户或组的ID。
描述场景方的 Enum.CreatorType,地方是由用户或组拥有还是由其他群组拥有。
描述服务器上运行的地方所属的体验ID。
无法使用。历史上将地方的 Enum.Genre 描述为在 Roblox 网站上设置。
运行游戏服务器实例的唯一标识。
代表服务器上玩家如何通过匹配处理。
描述服务器上运行的地方的 ID。
描述服务器运行的地方的版本。
描述服务器的私有服务器 ID,如果服务器是私有服务器或 reserved server 。
描述服务器是私有的情况下拥有私人有服务器的 。
对 Workspace 服务的参考。
方法
将一个函数绑定到服务器关闭之前调用。
返回包含任务调度程序执行的基本信息的表。
返回与给定内容 URL 相关的 Instances 阵列。
如果客户端第一次加载游戏已完成,返回真值。
将当前游戏实例的 DataModel.PlaceId 设置为指定的 placeId。
将当前游戏实例的 DataModel.GameId 设置为指定的 universeId。
返回指定类别的服务,如果已创建,则返回无效名称的错误。
返回服务与请求的类名称,如果不存在,创建它。
活动
当用户提示时发生火焰,并使用快捷键增加或减少图形质量。
当游戏第一次加载完成时,在客户端发生火焰。
当当前位置退出时发生火灾。
在服务创建时发射。
在服务即将被删除时发射。
属性
CreatorId
该属性描述了拥有场景方的用户或组的ID。如果 DataModel.CreatorType 属性是 '用户' 那么创建者ID将是场景方所有者的 Player.UserId如果 DataModel.CreatorType 是 '组' 那么创建者ID将是拥有该位置的组的I场景。
代码示例
This code sample will print an output when the user that owns the game, or a member of the group that owns the game joins the server.
To run this script, place it inside a Script in ServerScriptService
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
if game.CreatorType == Enum.CreatorType.User then
if player.UserId == game.CreatorId then
print("The place owner has joined the game!")
end
elseif game.CreatorType == Enum.CreatorType.Group then
if player:IsInGroup(game.CreatorId) then
print("A member of the group that owns the place has joined the game!")
end
end
end)
CreatorType
该属性描述了场景方的 Enum.CreatorType,地方是由用户或群组拥有还是否拥有。
如果 Enum.CreatorType 是 '用户',那么 DataModel.CreatorId 属性将描述拥有游戏的帐户的 UserId。如果创建者类型是 '组' , 那么它将描述组 ID。
代码示例
This code sample will print an output when the user that owns the game, or a member of the group that owns the game joins the server.
To run this script, place it inside a Script in ServerScriptService
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
if game.CreatorType == Enum.CreatorType.User then
if player.UserId == game.CreatorId then
print("The place owner has joined the game!")
end
elseif game.CreatorType == Enum.CreatorType.Group then
if player:IsInGroup(game.CreatorId) then
print("A member of the group that owns the place has joined the game!")
end
end
end)
Environment
GameId
该属性描述了服务器上运行的地方所属的体验ID。
还看到也看到
- DataModel.PlaceId , 描述服务器上运行的地方的ID
- DataModel.JobId , 这是运行中服务器游戏实例的唯一标识符
- TeleportService , 这是可以用于在游戏之间传输 Players 的服务
Genre
该属性已损坏且不应使用。
该属性历史上描述了地方的 Enum.Genre 被设置在 Roblox 网站上。
此属性以及 DataModel.GearGenreSetting 不再正常运行,因为 Roblox 网站上存在的类别未反映在 Enum.Genre 枚列中。因结果,尝试阅读此属性可能会发生错误。
JobId
该属性是运行游戏服务器实例的唯一标识符。它是一种通用唯一标识符 (UUID),意味着没有两个服务器,过去或现在,会有相同的ID。
在 Studio 中默认为空字符串。
还看到也看到
- TeleportService:GetPlayerPlaceInstanceAsync() 可用于检索用户当前服务器的 DataModel.JobId 。
- TeleportService:TeleportToPlaceInstance() 可用于将 Player 传送到特定服务器。
- DataModel.PrivateServerId 描述游戏服务器实例所属的私服ID。
- HttpService:GenerateGUID() , 一种可以用来生成自己UUID的函数。
MatchmakingType
该属性代表服务器上的玩家如何通过匹配处理。不同的 MatchmakingTypes 玩家无法在同一服务器上或进行传送。
请注意,此属性仅在服务器 DataModel 上有效,且将成为所有客户端的 Enum.MatchmakingType.Default 值,因此只能在服务器端 Script 中引用此属性。
PlaceId
该属性描述了服务器上运行的地方的 ID。
如果该地方尚未发布到 Roblox,该 ID 将与使用的模板匹配。
还看到也看到
- DataModel.GameId , 描述当前位置所属的体验ID
- DataModel.JobId , 这是运行中服务器游戏实例的唯一标识符
- TeleportService , 这是可以用于在地点之间运输 Players 的服务
PlaceVersion
该属性描述了服务器运行的地方的版本。
该版本号与场景方设置的 版本历史 部分中显示的版本号相对应。它不是 Roblox 客户端的当前版本。该属性对所有未发布的体验为 0。
当为地场景创建服务器实例时,它使用地场景的当前版本。如果在此服务器运行时更新位置,服务器将保持当前版本。
该属性可用于显示一个 ScreenGui 显示游戏当前版本到 Players 以协助调试。
代码示例
This code sample will place a simple GUI in the StarterGui showing the place version the server is running at.
To use this sample, place it inside a Script in ServerScriptService.
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("Server version: %s", placeVersion)
textLabel.Parent = versionGui
versionGui.Parent = StarterGui
PrivateServerId
该属性描述服务器的私有服务器 ID,如果服务器是私有服务器。
如果服务器不是私服,那么此属性将是空的字符串。
私有服务器
私服指向以关注中/正在关注内容:
- 私有服务器,用户可以从游戏页面购买
- 保留服务器、由开发者使用 TeleportService:ReserveServer() 创建的私服务器
私有服务器ID vs工作ID
服务器的私有服务器ID与 DataModel.JobId 不同。 JobId 是当前服务器实例的唯一标识符。
私有服务器(私有或保留服务器)可以随着时间的推移有多个服务器实例与之关联。这是因为,虽然只有一个服务器实例可以一次运行在私服上,但新的服务器实例可以在玩家加入和离开游戏时打开并关闭。例如,当没有人在服务器上游戏时,没有服务器实例运行。私有服务器ID将在所有这些服务器实例上保持一致,而 DataModel.JobId 将为每个独一无二。
还见:
- DataModel.PrivateServerOwnerId , 描述私服务器所有者的属性
- TeleportService:ReserveServer() , 一个创建保留服务器的函数
代码示例
DataModel.PrivateServerId and DataModel.PrivateServerOwnerId can be used to detect if the current server instance is a standard server, a VIP server or a reserved server.
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
该属性描述了服务器是私有的情况下 拥有 私人有服务器 的所有者。
如果服务器是标准或保留服务器,那么此属性将设置为 0。
这个属性可以用来确定是否 Player 是私服务器的所有者,例如:
local Players = game:GetService("Players")
-- 这是私人服务器吗?
if game.PrivateServerId ~= "" and game.PrivateServerOwnerId ~= 0 then
-- 听到新玩家被添加
Players.PlayerAdded:Connect(function(player)
-- 检查玩家是否是服务器所有者
if player.UserId == game.PrivateServerOwnerId then
print("The private server owner has joined the game")
end
end)
end
还见:
- DataModel.PrivateServerId , 描述私有和reserved servers的独特ID的属性
代码示例
DataModel.PrivateServerId and DataModel.PrivateServerOwnerId can be used to detect if the current server instance is a standard server, a VIP server or a reserved server.
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())
方法
BindToClose
将一个函数绑定到服务器关闭之前调用。如果绑定函数接受了参数,它将传递 Enum.CloseReason 指定服务器关闭的原因。
您可以通过多次调用 BindToClose() 来绑定多个函数。绑定的函数并行调用并在同一时间运行。
体验服务器在关闭之前等待 30 秒,所有绑定的函数都停止运行。在 30 秒后,即使函数仍在运行,服务器也会关闭。
要验证当前会话不在 Roblox Studio 中,请使用 RunService:IsStudio() 。这防止已绑定的函数在离线测试会话中完成运行。
当你使用 DataStoreService 时,你也应该使用 BindToClose 来绑定一个函数,将所有未保存的数据绑定到 DataStores 。这可以防止服务器意外关闭时数据丢失。
还见:
- Enum.CloseReason 因为体验服务器关闭的原因。
- PluginGui:BindToClose() , 将函数绑定到 PluginGui 关闭按钮。
参数
在体验服务器关闭之前调用的函数。如果绑定函数接受了参数,它将传递 Enum.CloseReason 指定服务器关闭的原因。
返回
代码示例
The following code sample is an example of how DataModel:BindToClose() can be used to save player data in the event of a server shutdown. In this example, player data is stored in a dictionary named playerData with UserIds as keys.
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
-- Avoid writing studio data to production and stalling test session closing
return
end
-- Reference for yielding and resuming later
local mainThread = coroutine.running()
-- Counts up for each new thread, down when the thread finishes. When 0 is reached,
-- the individual thread knows it's the last thread to finish and should resume the main thread
local numThreadsRunning = 0
-- Calling this function later starts on a new thread because of coroutine.wrap
local startSaveThread = coroutine.wrap(function(userId, sessionData)
-- Perform the save operation
local success, result = pcall(savePlayerDataAsync, userId, sessionData)
if not success then
-- Could implement a retry
warn(string.format("Failed to save %d's data: %s", userId, result))
end
-- Thread finished, decrement counter
numThreadsRunning -= 1
if numThreadsRunning == 0 then
-- This was the last thread to finish, resume main thread
coroutine.resume(mainThread)
end
end)
-- This assumes playerData gets cleared from the data table during a final save on PlayerRemoving,
-- so this is iterating over all the data of players still in the game that hasn't been saved
for userId, sessionData in pairs(allPlayerSessionDataCache) do
numThreadsRunning += 1
-- This loop finishes running and counting numThreadsRunning before any of
-- the save threads start because coroutine.wrap has built-in deferral on start
startSaveThread(userId, sessionData)
end
if numThreadsRunning > 0 then
-- Stall shutdown until save threads finish. Resumed by the last save thread when it finishes
coroutine.yield()
end
end
game:BindToClose(onServerShutdown)
The following example prints the close reason to the output. It prints Done after three seconds, and then allows Roblox to shut down the experience server.
The close reason matches one of the values in Enum.CloseReason.
game:BindToClose(function(closeReason)
print(`Closing with reason {closeReason}`)
task.wait(3)
print("Done")
end)
GetJobsInfo
返回包含任务调度程序执行的基本信息的表。
在计算中,任务调度器是负责在适当时间执行关键任务的系统。
您还可以在 Roblox Studio 的任务计划器窗口中找到实时任务调度器统计数据。
返回表中的第一个输入是包含可用统计(或标题)的参考词典。它具有以下格式:
{["name"] = "name",["averageDutyCycle"] = "averageDutyCycle",["averageStepsPerSecond"] = "averageStepsPerSecond",["averageStepTime"] = "averageStepTime",["averageError"] = "averageError",["isRunning"] = "isRunning",}
返回表中的后续条目包含包含任务调度任务计划程序执行的工作的上述统计数据的词典。例如:
{["name"] = "Heartbeat",["averageDutyCycle"] = 0,["averageStepsPerSecond"] = 0,["averageStepTime"] = 0,["averageError"] = 0,["isRunning"] = false,}
还见:
返回
包含任务调度程序执行的工作信息的表,请参阅上面的格式。
代码示例
Here is an example of iterating over the job info.
local jobInfo = game:GetJobsInfo()
local jobTitles = jobInfo[1]
table.remove(jobInfo, 1)
local divider = string.rep("-", 120)
print(divider)
warn("JOB INFO:")
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
GetObjects
该方法返回与给定内容 URL 相关的 Instances 阵列。它可用于从 Roblox 图书馆插入内容。由于它们没有与它们相关的 Sounds ,因此无法使用此方法插入 Instance 。它们只有一个内容 URL。
与 InsertService:LoadAsset() 不同,DataModel:GetObjects() 不需要资产被“信任”,即意味着资产不需要由登录用户拥有或由 Roblox 创建,才能插入。然而,如果资产不属于登录用户,它必须免费提供。
由于此功能的安全上下文,它只能由插件或命令栏使用。对于在 Scripts 和 LocalScripts 中可以使用的替代方案,请参阅 InsertService:LoadAsset() 。
参数
给定的内容 URL。
返回
与内容 URL 相关的 Instances 阵列。
代码示例
If you want to view a plugin's source code without installing it, you can use DataModel:GetObjects() to download the plugin. The code sample below includes a function that will take a plugin's website URL and insert the plugin into the currently selected Instance or the Workspace.
Due to GetObjects' security context, this function can only be used in the command line or in a plugin.
local Selection = game:GetService("Selection")
local WEB_URL = "plugin URL here"
local function downloadPlugin(webURL)
-- get the content URL
local contentID = string.match(webURL, "%d+")
local contentURL = "rbxassetid://" .. contentID
-- download the objects
local objects = game:GetObjects(contentURL)
-- decide where to parent them
local selection = Selection:Get()
local parent = #selection == 1 and selection[1] or workspace
-- parent the objects
for _, object in pairs(objects) do
object.Parent = parent
end
end
downloadPlugin(WEB_URL)
The content ID of a Decal on the Roblox website is associated with a Decal Instance rather than the actual content ID of the texture.
The code below, will use DataModel:GetObjects() to insert Decal objects into place and read their Decal.Texture property to obtain the image content IDs.
To use this code sample, enter the web URLs of the decals you'd like to convert into the array named IMAGES (as strings). A dictionary with the converted textures will be outputted.
local IMAGES = {
-- Insert Decal web URLs in an array here (as strings)
}
-- open the dictionary
local outputString = "textures = {"
-- utility function to add a new entry to the dictionary (as a string)
local function addEntryToDictionary(original, new)
outputString = outputString
.. "\n" -- new line
.. " " -- indent
.. '["'
.. original
.. '"]' -- key
.. ' = "'
.. new
.. '",' -- value
end
print("Starting conversion")
for _, webURL in pairs(IMAGES) do
-- get the content URL
local contentID = string.match(webURL, "%d+")
local contentURL = "rbxassetid://" .. contentID
local success, result = pcall(function()
local objects = game:GetObjects(contentURL)
return objects[1].Texture
end)
if success then
addEntryToDictionary(webURL, result)
else
addEntryToDictionary(webURL, "Error downloading decal")
end
task.wait()
end
print("Conversion complete")
-- close the dictionary
outputString = outputString .. "\n}"
-- print the dictionary
print(outputString)
IsLoaded
当游戏中所有初始 Instances 复制到客户端后,此函数返回真实。
除非它们被父辈到 ReplicatedFirst , LocalScripts 在游戏加载之前不会运行。以下代码片段,从 LocalScript 在 ReplicatedFirst 运行直到游戏加载:
if not game:IsLoaded() thengame.Loaded:Wait()end
还见:
- 复制顺序对加载过程的更详细摘要。
- DataModel.Loaded , 游戏加载时触发的事件
- Instance:WaitForChild() , 一种可以用来等待个人 Instance 重复而不需要等待整个游戏加载完成的函数。
返回
客户端是否已第一次完成加载游戏。
代码示例
This sample demonstrates a custom loading screen with a basic TextLabel. The code should be placed in a LocalScript within ReplicatedFirst. To expand on this sample with loading screen animations, see the Custom Loading Screens article.
local Players = game:GetService("Players")
local ReplicatedFirst = game:GetService("ReplicatedFirst")
local player = Players.LocalPlayer
local playerGui = player:WaitForChild("PlayerGui")
-- Create a basic loading screen
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 = "Loading"
textLabel.TextSize = 28
textLabel.Parent = screenGui
-- Parent entire screen GUI to player GUI
screenGui.Parent = playerGui
-- Remove the default loading screen
ReplicatedFirst:RemoveDefaultLoadingScreen()
--wait(3) -- Optionally force screen to appear for a minimum number of seconds
if not game:IsLoaded() then
game.Loaded:Wait()
end
screenGui:Destroy()
SetPlaceId
这个函数将游戏实例的 DataModel.PlaceId 设置为指定的 placeId。
设置 both DataModel.PlaceId 和 DataModel.GameId 是必需的,才能在地点未发布时访问 DataStoreService,例如本地 .rbxl 文件。请参阅下面的示例。请注意,从 Studio 获得 访问需要在 游戏设置 中的 安全 面板中启用 启用 Studio 访问 API 服务 设置。
local DataStoreService = game:GetService("DataStoreService")-- 通过将 PlaceId 设置为 placeId 和 GameId 设置为 universeId 来访问数据存储 "数据"。game:SetPlaceId(placeId)game:SetUniverseId(universeId)local dataStore = DataStoreService:GetDataStore("Data")
参数
设置 DataModel.PlaceId 的 ID。
返回
SetUniverseId
这个函数将当前游戏实例的 DataModel.GameId 设置为给定的 宇宙ID。这对于测试尚未发布到 Roblox 的本地 .rbxl 文件很有用。
要在未发布的场景方访问 DataStoreService ,必须设置 both DataModel:SetUniverseId() 和 DataModel:SetPlaceId() 。
参数
设置 DataModel.GameId 的 ID。
返回
活动
GraphicsQualityChangeRequest
当用户使用快捷键提示增加或减少图形质量时,发生火焰。
该事件在以下条件下发生:
- 如果用户按下 F10 , 这个事件使用 betterQuality 参数发射 true 。
- 如果用户按下 Shift F10 , 这个事件会发射一个 betterQuality 参数的 false 。
该事件不提供当前图形质量等级或覆盖所有图形质量更新。例如,在核心 GUI 逃生菜单中进行的更改不会被注册。
您可以使用以下代码片段来检索用户的 :
UserSettings():GetService("UserGameSettings").SavedQualityLevel
如果用户的图形设置设置为自动,那么 Enum.SavedQualitySetting 将是 Automatic 。目前,开发人员无法可靠地获取用户机器的当前图形质量等级。
参数
用户是否提示了增加(true)或减少(false)图形质量。
代码示例
game.GraphicsQualityChangeRequest:Connect(function(betterQuality)
if betterQuality then
print("The user has requested an increase in graphics quality!")
else
print("The user has requested a decrease in graphics quality!")
end
end)
Loaded
当游戏中所有初始 Instances 复制到客户端完成时,该事件会在客户端发射。
除非它们被父辈到 ReplicatedFirst , LocalScripts 在游戏加载之前不会运行。以下代码片段,从 LocalScript 在 ReplicatedFirst 运行直到游戏加载:
if not game:IsLoaded() thengame.Loaded:Wait()end
还见:
- 复制顺序对加载过程的更详细摘要。
- DataModel.Loaded , 游戏加载时触发的事件
- Instance:WaitForChild() , 一种可以用来等待个人 Instance 重复而不需要等待整个游戏加载完成的函数。