主题
World
World 编辑世界服务。 管理场景中的所有 Unit,提供查找、创建等操作。
Overview
世界服务用于管理当前场景中的单位对象,是场景单位体系的统一入口。它提供按名称查找单位、获取全部后代单位、按单位类型批量查询,以及通过资源或类型直接创建单位的能力,所有接口返回的对象均为单位封装。
Get by:
lua
-- @runtime client
local service = editor:GetService("World")Public
FindFirstChild
在世界场景内按单位名称查找单位,返回第一个匹配到该名称的单位。
参数
| 参数 | 类型 | 说明 |
|---|---|---|
name | String | 要查找的单位名称 |
返回值
| 类型 | 说明 |
|---|---|
Unit | 找到的单位;未找到时返回 nil |
调用 FindFirstChild
lua
-- @runtime client
local world = editor:GetService("World")
local name = "default" -- String
local result = world:FindFirstChild(name) -- 返回 Unit
if result ~= nil then
print("调用成功,结果: " .. tostring(result))
endGetDescendants
返回当前场景中的所有单位,结果存放在数组中。
返回值
| 类型 | 说明 |
|---|---|
Array | 场景中的所有单位数组 |
调用 GetDescendants
lua
-- @runtime client
local world = editor:GetService("World")
local result = world:GetDescendants() -- 返回 Array
if result ~= nil then
for index, item in ipairs(result) do
print(index, item)
end
endCreateAsset
在世界场景内创建资产单位,并根据传入的位置信息放置到对应坐标;创建结果以单位列表形式返回。
参数
| 参数 | 类型 | 说明 |
|---|---|---|
contentId | String | 预设资产 ID,可通过 PrefabService:CreatePrefab 创建后获取 |
pos | Vector3 | 创建位置(世界坐标) |
options | Table | 创建选项:rot(旋转)、scale(缩放),均为可选 |
返回值
| 类型 | 说明 |
|---|---|
Array | 创建的单位数组 |
加载预设并清理本次创建的单位
lua
-- @runtime client
local world = editor:GetService('World')
local function loadAndInspectAsset(assetId)
if assetId == nil or assetId == '' then return end
local units = world:CreateAsset(assetId)
print('加载单位数量:', units and #units or 0)
for _, unit in ipairs(units or {}) do
unit:Destroy()
end
end
-- 调用方把项目配置中的真实预设资源 ID 传给 loadAndInspectAssetCreateUnit
按指定的单位类型在场景中创建单位,创建出的单位以数组形式返回。
注意: CreateUnit 返回 Unit 数组,而不是单个 Unit。示例会在当前场景创建一个临时单位;验证后可在场景层级中删除。
参数
| 参数 | 类型 | 说明 |
|---|---|---|
unitType | String | 要创建的单位类型名称(如 WorldUnit、ModelUnit) |
values | Table | 创建参数:Position(位置)、Rotation(旋转)、Scale(缩放)、AssetId(直接指定预设资产 ID),均为可选 |
返回值
| 类型 | 说明 |
|---|---|
Array | 创建的单位数组;该类型无可用预设且未传 AssetId 时返回空数组 |
创建临时世界单位并读取返回数组
lua
-- @runtime client
local world = editor:GetService("World")
local units = world:CreateUnit("WorldUnit", { Name = "DocumentationExampleUnit" })
local unit = units and units[1]
if unit ~= nil then
print("已创建:", unit.Name)
endGetUnitsByUnitType
按单位类型筛选场景中的单位,并返回全部匹配单位的数组。
参数
| 参数 | 类型 | 说明 |
|---|---|---|
unitType | String | 要查询的单位类型名称 |
exact | Bool | 是否精确匹配;false 时同时返回继承子类型 |
返回值
| 类型 | 说明 |
|---|---|
Array | 匹配到的单位数组,无匹配时返回空数组 |
调用 GetUnitsByUnitType
lua
-- @runtime client
local world = editor:GetService("World")
local unitType = "default" -- String
local exact = false -- Bool
local result = world:GetUnitsByUnitType(unitType, exact) -- 返回 Array
if result ~= nil then
for index, item in ipairs(result) do
print(index, item)
end
end