DataModel

顯示已棄用項目

*此內容是使用 AI(Beta 測試版)翻譯,可能含有錯誤。若要以英文檢視此頁面,請按一下這裡

無法建立

數據模型(通常稱為之後使用來存取它的全球變量)是Roblox的父子階層的根。它的直接兒女是服務,例如 WorkspaceLighting ,這些服務是 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
  • 平行寫入

    如果給定的 className 已創建服務,返回指定的服務,如果名稱無效,錯誤。

  • 返回要求的類別名稱的服務,如果不存在,則創建它。

活動

活動 繼承自 ServiceProvider

屬性

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

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 屬性將描述擁有遊戲的帳戶的 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

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)

Environment

唯讀
未複製
Roblox 指令碼安全性
平行讀取

GameId

唯讀
未複製
平行讀取

此屬性描述服務器上運行的地方所屬的體驗ID。

也見「也見」

唯讀
未複製
平行讀取

此屬性已斷裂且不應使用。

這個屬性歷史上描述了地方的 Enum.Genre 在 Roblox 網站上設置。

此屬性,以及 DataModel.GearGenreSetting ,由於 Roblox 網站上存在的類型未反映在 Enum.Genre 枚列中,因此無法正常運作。因結果,嘗試閱讀此屬性可能會發生錯誤。

JobId

唯讀
未複製
平行讀取

此屬性是運行中遊戲伺服器實個體、實例的獨一標示符。它是一個通用獨一標識符 (UUID),意味著過去或現在的兩個伺服器永遠不會有相同的ID。

在 Studio 中預設為空字串。

也見「也見」

MatchmakingType

唯讀
未複製
平行讀取

此屬性代表伺服器上的玩家如何通過匹配來處理。不同的玩家 MatchmakingTypes 無法在同一服務器上或進行傳送。

請注意,此屬性只適用於伺服器 DataModel ,因此所有客戶端的值都會是 Enum.MatchmakingType.Default 值,因此只能在服務器端 Script 內參考此屬性。

PlaceId

唯讀
未複製
平行讀取

此屬性描述服務伺服器上運行的地方的ID。

如果該地點尚未發布到 Roblox,此 ID 將與使用的樣板相對應。

也見「也見」

PlaceVersion

唯讀
未複製
平行讀取

此屬性描述服務器運行的地方版本。

此版本號與空間置設定的 版本歷史 部分所顯示的版本號相對應。它不是 Roblox 客戶的現行版本。此屬性對所有未發布的體驗為 0。

當為地空間創建服務器實例時,會使用該空間方的當前版本。如果在此伺服器運行時更新位置,伺服器將保持在當前版本。

此屬性可用於顯示 顯示遊戲當前版本以協助進行調試。

範例程式碼

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,如果服務器是私有伺服器。

如果伺服器不是私人伺服器,則此屬性將是空字串。

私人伺服器

私人伺服器指向以追蹤中內容:

私人伺服器ID vs工作ID

服務器的私有伺服器ID與DataModel.JobId不同。JobId是當前服務器實個體、實例的唯一標識符。

私人伺服器(私人或保留伺服器)可能會隨著時間過去與它們相關的多個伺服器實例。這是因為,雖然只有一個伺服器實例可以一次運行在私人伺服器上,但新的伺服器實例可以在玩家加入和離開遊戲時開啟和關閉。例如,當沒有人在伺服器上遊玩時,就沒有伺服器實例運行。私人伺服器ID將在所有這些伺服器實例上一致,而DataModel.JobId將為每個獨一無二。

也見:

範例程式碼

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

唯讀
未複製
平行讀取

此屬性描述了擁有 私人伺服器 的 私人伺服器 如果伺服器是私人的。

如果伺服器是標準或保留伺服器,則此屬性將設為 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 並永遠不會是 nil

方法

BindToClose

()

將功能綁定到服務器關閉之前呼叫。如果綁定的函數接受參數,它會傳送 Enum.CloseReason 指定服務器關閉的原因。

您可以重複呼叫 BindToClose() 來綁定多個功能。綁定的功能將並行呼叫並在同一時間運行。

經驗服務器等待 30 秒,所有綁定的功能停止運行,然後關閉。在 30 秒後,即使功能仍在運行,伺服器也會關閉。

要驗證當前會話不在 Roblox Studio 中,請使用 RunService:IsStudio() 。這會防止綁定的函數在離線測試會話中完成運行。

當您使用 DataStoreService 時,您也應該使用 BindToClose 來綁定一個函數,將所有未儲存的資料綁定到 DataStores 。這樣可以防止伺服器不期而至地關閉,導致數據損失。

也見:

參數

function: function

在體驗伺服器關閉之前呼叫的功能。如果綁定的函數接受參數,它會傳送 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.

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
外掛程式安全性

此方法返回與給定內容 URL 相關的 Instances 數組。它可以用來插入 Roblox 圖書館的內容。無法使用此方法插入 Sounds ,因為它們沒有與它們相關的 Instance 並只有內容 URL。

InsertService:LoadAsset() 不同,DataModel:GetObjects() 不需要資產被「信任」,即意味著資產不需要由登入的使用者擁有或由 Roblox 創建,才能被插入。然而,如果資產不屬於登入的使用者,它必須自由可用。

由於此功能的安全上下文,只能由插件或指令欄使用。對於在 ScriptsLocalScripts 中可使用的替代方案,請參閱 InsertService:LoadAsset()

參數

url: ContentId

指定的內容 URL。

預設值:""

返回

Instances

與內容 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.

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

當遊戲中所有初始 Instances 都複製到客戶端完成時,此功能返回真值。

除非它們被父輩到 ReplicatedFirst , LocalScripts 否則不會在遊戲載入時運行。以下代碼片段,從 LocalScriptReplicatedFirst 運行直到遊戲載入:


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

()
外掛程式安全性

此功能將遊戲實例的 DataModel.PlaceId 設置為指定的 placeId

設定兩個 DataModel.PlaceIdDataModel.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")

參數

placeId: number

設置 DataModel.PlaceId 的ID。

預設值:""

返回

()

SetUniverseId

()
外掛程式安全性

此功能將現有遊戲實例的 DataModel.GameId 設置為指定的 宇宙ID。當測試未發布到 Roblox 的本地 .rbxl 文件時,這很有用。

若要在未發布的空間方存取 DataStoreService,必須設定兩個 DataModel:SetUniverseId()DataModel:SetPlaceId()

參數

universeId: number

設置 DataModel.GameId 的ID。

預設值:""

返回

()

活動

GraphicsQualityChangeRequest

當使用熱鍵提示增加或減少圖形品質時,發生火災。

此事件在下列條件下發生:

  • 如果使用者按下 F10 , 此事件會使用 betterQuality 參數發射 true
  • 如果使用者按下 Shift F10 , 這個事件會使用 betterQuality 參數 false 發射。

此事件不提供當前圖形質量等級或覆蓋所有圖形質量更新。例如,在核心 GUI 逃生選單中所做的變更未被註冊。

您可以使用下列片段 UserGameSettings 來恢復使用者的 Enum.SavedQualitySetting


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

如果使用者的圖形設定設為自動,則 Enum.SavedQualitySetting 將會是 Automatic 。目前沒有辦法讓開發人員可靠地獲得使用者機器的當前圖形品質等級。

參數

betterQuality: boolean

使用者是否提示增加(真實)或減少()圖形品質。


範例程式碼

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 在遊戲中複製到客戶端完成時,此事件會在客戶端發射。

除非它們被父輩到 ReplicatedFirst , LocalScripts 否則不會在遊戲載入時運行。以下代碼片段,從 LocalScriptReplicatedFirst 運行直到遊戲載入:


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

也見: