DataModel

显示已弃用

*此内容使用人工智能(Beta)翻译,可能包含错误。若要查看英文页面,请点按 此处

无法创建

数据模型 (通常称为 game 后的全球变量) 是 Roblox 的父子关系层的根。其直接子女是工作间务,例如 Workspace 和 1> Class.Lighting1>,作为 Roblox 游戏的基础组成部分。

代码示例

Demonstrates using game, the root instance of DataModel, to get services such as Workspace and Lighting.

GetService()

local Workspace = game:GetService("Workspace")
local Lighting = game:GetService("Lighting")
-- Examples of modifying properties of these services
Workspace.Gravity = 20
Lighting.ClockTime = 4

概要

属性

方法

继承自ServiceProvider方法
  • 写入并联

    如果已经创建,返回指定的服务名,如果是一个无效名称,则会发生错误。

  • 返回服务,要求指定的类别名,如果它不存在,创建它。

活动

继承自ServiceProvider活动

属性

CreatorId

只读
未复制
读取并联

此属性描述场景方所有者的用户或组的ID。如果DataModel.CreatorType属性是“用户”,那么CreatorId就会是场景方所有者的Player.UserId。如果2>Class.DataModel.CreatorType2>是5>“群组

代码示例

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

Detect when the place owner joins the game

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 属性将描述游戏所拥有的帐户的 1> Class.Player.UserId|UserId1> 。如果 创建器类型是 4> '群组'4> ,那么它将描述群组 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

Detect when the place owner joins the game

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)

GameId

只读
未复制
读取并联

此属性描述服务器上运行的地方的体验ID。

资产管理器 在 Roblox Studio 的右上角找到。使用 Roblox Studio 时,如果地方尚未发布到 Roblox,游戏Id 将与使用的模板匹配。

还请参阅:

只读
未复制
读取并联

此属性已损坏,不应该用它。

这个属性之前描述了Enum.Genre这个地方在 Roblox 网站上设置的状态。

此属性,以及 DataModel.GearGenreSetting ,在 Roblox 网站上存在的音乐类型不再正确地由于音乐类型在 Enum.Genre 枚列表中反映。因结果,尝试读取此属性可能会发生错误。

JobId

只读
未复制
读取并联

此属性是运行游戏服务器实例的唯一标识。它是一个唯一的标识(UUID),意味着在过去或现在的两个服务器上,永远不会有两个相同的ID。

将 Studio 中的空串默认为空。

还见

PlaceId

只读
未复制
读取并联

此属性描述在服务器上运行的地方的 ID。

如果该地方已发布到 Roblox,此 ID 可以通过在 Studio 的 资产管理器 中,右击该地方并选择 复制到剪贴板 来找到。

如果该地方尚未发布到 Roblox,此 ID 将与使用的模板匹配。

还见

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.

Server version number 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("Server version: %s", placeVersion)
textLabel.Parent = versionGui
versionGui.Parent = StarterGui

PrivateServerId

只读
未复制
读取并联

此属性描述服务器的私人服务器ID,如果服务器是私人服务器。

如果服务器不是私人服务器,那么此属性将是一个空的字符串。

私人服务器

私人服务器通常指以关注中/正在关注:

PrivateServerId vs 工作Id

服务器的私人服务器ID与 DataModel.JobId 不同。 JobId 是当前服务器实例的唯一标识。

私人服务器 (私人或预留服务器) 可以有多个服务器实例在与它们关联时间过长。这是因为,虽然只有一个服务器实例可以同时运行在私人服务器上,但新服务器实例可以打开和关闭,当玩家加入并离开游戏。 例如,无论有多少服务器实例不在运行,私人服务器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.

Detecting Private Servers

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

只读
未复制
读取并联

这个属性描述 UserIdPlayer,如果服务器是私人服务器,它的私人服务器 Class.Player.Server 。

如果服务器是标准或预留服务器,这个属性将设置为 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 and DataModel.PrivateServerOwnerId can be used to detect if the current server instance is a standard server, a VIP server or a reserved server.

Detecting Private Servers

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())

Workspace

只读
未复制
读取并联

工作区属性是一个引用 Workspace 服工作间的引用。

这个属性总是指向 Workspace ,它永远不会是

Class.Workspace 也可以使用全球变量 workspaceServiceProvider:GetService() 函数来访问。例如:


workspace -- 一个全球变量
game.Workspace -- DataModel 的属性 (游戏)
game:GetService("Workspace") -- workspace is a service

方法

BindToClose

void

将一个函数绑定在服务器关闭前调用。如果该绑定的函数接受参数,它将通过 Enum.CloseReason 描述服务器关闭的理由。

您可以通过调用 BindToClose() 多次来绑定多个函数。边界函数是并行调用,并且在同一时间运行。

体验服务器在关闭前等待 30 秒,直到所有关联函数停止运行。 在 30 秒后,服务器仍然关闭,即使功能仍然运行。

要验证当前会话不在 Roblox Studio 中,请使用 RunService:IsStudio()。这防止在线测试会话完成后的关联函数。

当您使用 DataStoreService 时,您还应该使用 BindToClose 来将所有未保存的数据绑定到 DataStores 。这防止了服务器在意外关闭时丢失数据。

还请参阅:

参数

function: function

体验服务器关闭前,调用一个函数。如果该绑定函数接受参数,它将通过 Enum.CloseReason 传递服务器关闭的理由。


返回

void

代码示例

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.

Saving player data before shutting down

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.

Binding to and Handling Game Shutdown

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.

Getting Jobs 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

Instances
插件安全性

此方法返回一个 Instances 与给定内容 URL 关联的阵列。它可以用于插入 Roblox 库存中的内容。不能用此方法插入 Sounds ,因为它们没有与它们关联的 Instance

InsertService:LoadAsset() 不同,DataModel:GetObjects() 不需要要求资产“信任”,即可将资产插入。如果资产不是由登录用户拥有或创建,它必须是免费可用的。

由于该功能的安全上下文,它只能由插件或命令栏使用。 为了在 ScriptsLocalScripts 中使用的替代方案,请参阅 InsertService:LoadAsset()

参数

url: ContentId

指定的内容 URL。


返回

Instances

Class.Instance|Instances 阵列,与内容 URL 关联。

代码示例

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.

View a plugin's source code

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.

Batch convert decal IDs

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

此函数返回 true 如果客户端第一次载入游戏完成。

当所有初始 Instances 在游戏中复制到客户端时,此函数将返回 true。

除非它们被父级到 ReplicatedFirstLocalScripts 将不会在游戏未加载时运行。 以下代码从一个 LocalScript 在 1>Class.ReplicatedFirst1> 中运行:


if not game:IsLoaded() then
game.Loaded:Wait()
end

还请参阅:


返回

客户端是否已经完成游戏的第一次加载。

代码示例

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.

Custom Loading Screen

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

void
插件安全性

此函数将游戏实例的 DataModel.PlaceId 设置为指定的 placeId

设置 both DataModel.PlaceIdDataModel.GameId 是必要的,才能在 DataStoreService 中使用地方,例如 local


local DataStoreService = game:GetService("DataStoreService")
-- 通过将 PlaceId 设置为 placeId 和 GameId 为 universeId 来访问数据存储“数据”。
game:SetPlaceId(placeId)
game:SetUniverseId(universeId)
local dataStore = DataStoreService:GetDataStore("Data")

参数

placeId: number

设置 DataModel.PlaceId 的 ID。


返回

void

SetUniverseId

void
插件安全性

此函数将当前游戏实例的 DataModel.GameId 设置为 Class.DataModel.GameId 的给定 宇宙Id。 这很有用,当测试本地 .rbxl 文件,它们尚未发布到 Roblox。

要在未发布的场景方访问 DataStoreService,必须设置 DataModel:SetUniverseId()DataModel:SetPlaceId()

参数

universeId: number

设置 DataModel.GameId 的 ID。


返回

void

活动

GraphicsQualityChangeRequest

用户提示增加或减少图形质量时,发射。

此事件在以下条件下触发:

  • 如果用户按下 F10 ,此事件将发生,并且使用 betterQuality 参数的 true
  • 如果用户按下 Shift F10 ,此事件会发生使用 betterQuality 参数的 0> force0> 。

此事件不提供当前的图形质量级别或覆盖所有更新到图形质量。例如,在核心 GUI 逃生菜单中所做的更改不会注册。

您可以使用 Enum.SavedQualitySetting 用以下代码恢复用户的 UserGameSettings


UserSettings():GetService("UserGameSettings").SavedQualityLevel

如果用户的图形设置设置为自动,那么 Enum.SavedQualitySetting 将是 Automatic 。目前没有方法可以让开发人员获得用户的机器的当前图形质量级。

参数

betterQuality: bool

用户是否提示了增加 ( 真的 ) 或减少 ( 假的 ) 在图形质量上。


代码示例

Handling User Changes in Graphics Quality

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 完成复制到客户端后,都会发生。

除非它们被父级到 ReplicatedFirstLocalScripts 将不会在此事件发生时运行。 以下代码从一个 LocalScript 在 1>Class.ReplicatedFirst1> 中运行,会在游戏加载完成后返回:


if not game:IsLoaded() then
game.Loaded:Wait()
end

还请参阅: