Skip to content

ReplicatedStorage ​

ReplicatedStorage 复制仓库服务。管理复制容器下的所有 Unit,提供查找、创建等操作。

概览 ​

ReplicatedStorage 是服务端与客户端共享的复制容器,其子单位会自动同步到客户端,但不会创建物理刚体或渲染模型。

Get by:

lua
-- @runtime editor
local service = editor:GetService("ReplicatedStorage")

函数 ​

FindFirstChild ​

按名称(name)查找 ReplicatedStorage 下第一个匹配的子单位,找到时返回该单位,未找到时返回 nil。

参数

参数类型说明
nameString要查找的单位名称

返回值

类型说明
Unit找到的单位;未找到时返回 nil

按名称查找复制仓库中的单位并用 GetDescendants 复核

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 .. " 的单位,可能尚未同步到客户端")
end
local allUnits = replicatedStorage:GetDescendants()
print("容器下单位总数:", #allUnits)
for index, item in ipairs(allUnits) do
    print("单位", index, tostring(item))
end

GetDescendants ​

获取 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))
end

CreateAsset ​

根据内容 ID(contentId)与位置(pos)创建资产单位,可通过可选的 options 表传入附加参数,返回本次创建出来的单位数组。

参数

参数类型说明
contentIdString预设资产 ID,可通过 PrefabService:CreatePrefab 创建后获取
posVector3创建位置(世界坐标)
optionsTable创建选项: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 传给 createFromAsset

CreateUnit ​

按单位类型名(unitType)创建单位,可通过可选的 values 表提供初始值,返回创建出的单位数组;该类型无可用预设且未传 AssetId 时返回空数组。

参数

参数类型说明
unitTypeString要创建的单位类型名称(如 WorldUnit、ModelUnit)
valuesTable创建参数:Position(位置)、Rotation(旋转)、Scale(缩放)、AssetId(直接指定预设资产 ID),均为可选

返回值

类型说明
Array创建的单位数组;该类型无可用预设且未传 AssetId 时返回空数组

创建 WorldUnit 并清理

lua
-- @runtime editor
local storage = editor:GetService("ReplicatedStorage")
local units = storage:CreateUnit("WorldUnit", {})
for _, unit in ipairs(units or {}) do
    print("已创建:", unit)
    unit:Destroy()
end

GetUnitsByUnitType ​

按单位类型名(unitType)获取匹配的单位,exact 为可选参数,返回匹配到的单位数组,无匹配时返回空数组。

参数

参数类型说明
unitTypeString要查询的单位类型名称
exactBool是否精确匹配;false 时同时返回继承子类型

返回值

类型说明
Array匹配到的单位数组,无匹配时返回空数组

查询 WorldUnit

lua
-- @runtime editor
local storage = editor:GetService("ReplicatedStorage")
local units = storage:GetUnitsByUnitType("WorldUnit", true)
print("数量:", #units)