主题
ReplicatedStorage
ReplicatedStorage 复制仓库服务。管理复制容器下的所有 Unit,提供查找、创建等操作。
概览
ReplicatedStorage 是 SE 编辑器专属的复制仓库服务,通过 editor:GetService("ReplicatedStorage") 获取。其下单位会自动同步到所有客户端(服务器→客户端单向),但不会为其创建物理刚体和渲染模型,适合存放客户端与服务器共享的数据对象,例如 RemoteEvent 与配置数据。编辑时操作限定在容器子树内:查询只返回容器下的单位,创建的单位会自动挂到容器下,并在编辑器内默认隐藏;返回的单位为 Unit 对象封装,销毁、克隆与父子操作与 World 统一。
Get by:
lua
-- @runtime editor
local service = editor:GetService("ReplicatedStorage")函数
FindFirstChild
在 ReplicatedStorage 容器子树内按名称查找第一个匹配的单位,找不到时返回 nil。
参数
| 参数 | 类型 | 说明 |
|---|---|---|
name | String | 要查找的单位名称 |
返回值
| 类型 | 说明 |
|---|---|
Unit | 找到的单位;未找到时返回 nil |
在容器子树内按名称查找并核对全部单位
lua
-- @runtime editor
local replicatedStorage = editor:GetService("ReplicatedStorage")
local targetName = "SharedConfig"
local unit = replicatedStorage:FindFirstChild(targetName)
if unit ~= nil then
print("查找成功:", tostring(unit))
else
print("容器子树内未找到名称为 " .. targetName .. " 的单位,请确认该单位已挂到 ReplicatedStorage 容器下")
end
local allUnits = replicatedStorage:GetDescendants()
print("容器下单位总数:", #allUnits)
for index, item in ipairs(allUnits) do
print("单位", index, tostring(item))
endGetDescendants
获取 ReplicatedStorage 服务容器下的所有单位,并以单位数组的形式返回。
返回值
| 类型 | 说明 |
|---|---|
Array | 容器下的所有单位数组 |
获取容器下所有单位并统计指定类型单位数量
lua
-- @runtime editor
local replicatedStorage = editor:GetService("ReplicatedStorage")
local units = replicatedStorage:GetDescendants()
print("容器下单位总数:", #units)
for index, item in ipairs(units) do
print("单位", index, tostring(item))
end
local typedUnits = replicatedStorage:GetUnitsByUnitType("WorldUnit", true)
print("类型为 WorldUnit 的单位数量:", #typedUnits)
for index, item in ipairs(typedUnits) do
print("WorldUnit", index, tostring(item))
endCreateAsset
在 ReplicatedStorage 服务上创建资产单位:按给定的资产内容标识 contentId 与位置 pos 生成单位,并以单位数组的形式返回创建结果。第三个参数 options 为可选表,用于在创建时附带可选配置。
注意: contentId 必须是项目中真实存在的预设资产 ID。创建出的单位会自动挂在 ReplicatedStorage 容器下,并在编辑器内默认隐藏。
参数
| 参数 | 类型 | 说明 |
|---|---|---|
contentId | String | 预设资产 ID;可由 PrefabService:CreatePrefabFromUnit 把场景中已搭好的单位结构固化为预设后取得。 |
pos | Vector3 | 创建位置(世界坐标) |
options | Table | 创建选项:rot(旋转)、scale(缩放),均为可选 |
返回值
| 类型 | 说明 |
|---|---|
Array | 创建的单位数组 |
用项目预设 ID 创建复制资源
lua
-- @runtime editor
local storage = editor:GetService("ReplicatedStorage")
local function createFromAsset(assetId)
if assetId == nil or assetId == "" then return end
local units = storage:CreateAsset(assetId, Vector3.New(0, 0, 0))
for _, unit in ipairs(units or {}) do
print("已创建:", unit)
end
end
-- 把项目中的真实预设资源 ID 传给 createFromAssetGetUnitsByUnitType
按单位类型在 ReplicatedStorage 服务中筛选单位,返回匹配到的单位数组;无匹配时返回空数组。第二个参数 exact 为可选布尔值,用于控制类型匹配方式。
参数
| 参数 | 类型 | 说明 |
|---|---|---|
unitType | String | 要查询的单位类型名称 |
exact | Bool | 是否精确匹配;false 时同时返回继承子类型 |
返回值
| 类型 | 说明 |
|---|---|
Array | 匹配到的单位数组,无匹配时返回空数组 |
查询 WorldUnit
lua
-- @runtime editor
local storage = editor:GetService("ReplicatedStorage")
local units = storage:GetUnitsByUnitType("WorldUnit", true)
print("数量:", #units)