Skip to content

Selection ​

Selection 选择管理服务。 管理编辑器中当前选中的 Unit,支持获取、替换、追加和移除选中。

概览 ​

Selection 是编辑器中的选择管理服务,用于统一读写当前被选中的 Unit 集合。它提供获取全部选中项、整体替换选中集合、向集合追加选中项以及移除选中项的能力,是批量处理选中对象的统一入口。

Get by:

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

函数 ​

Get ​

Get 是 Selection 服务提供的成员函数,标题为“获取当前选中”。该函数不需要传入任何参数,调用后返回当前选中的单位数组,数组元素类型为 Unit。

返回值

类型说明
Array当前选中的单位数组

获取当前选中单位并遍历输出

lua
-- @runtime editor
local selection = editor:GetService("Selection")

local units = selection:Get()
print("当前选中数量:", #units)

for index, unit in ipairs(units) do
    print(string.format("第 %d 个选中单位: %s", index, tostring(unit)))
end

追加选中后查询验证并恢复原选中

lua
-- @runtime editor
local selection = editor:GetService("Selection")
local world = editor:GetService("World")

local previous = selection:Get()
print("操作前选中数量:", #previous)

local unit = world:CreateUnit("WorldUnit", {})
if unit == nil then
    print("单位创建失败,跳过追加操作")
    return
end

selection:Add({ unit })
local afterAdd = selection:Get()
print("追加后选中数量:", #afterAdd)

selection:Set(previous)
local afterRestore = selection:Get()
print("恢复后选中数量:", #afterRestore)

Set ​

用传入的单位数组替换当前选中集合,直接设定新的选中内容。

参数

参数类型说明
unitsArrayUnit 对象列表

调用 Set

lua
-- @runtime editor
local selection = editor:GetService("Selection")
local units = {}  -- Array
selection:Set(units)
print("已调用 Set", units)

Add ​

将传入的单位数组追加到当前选中集合中。

参数

参数类型说明
unitsArrayUnit 对象列表

新增单位到当前选中集合

lua
-- @runtime editor
local selection = editor:GetService('Selection')
local world = editor:GetService('World')
local previous = selection:Get()
local unit = world:CreateUnit('WorldUnit', {})
if unit == nil then return end
selection:Add({unit})
print('追加后的选中数量:', #selection:Get())
selection:Set(previous)
unit:Destroy()

Remove ​

从当前选中集合中移除传入的单位。

参数

参数类型说明
unitsArrayUnit 对象列表

调用 Remove

lua
-- @runtime editor
local selection = editor:GetService("Selection")
local units = {}  -- Array
selection:Remove(units)
print("调用完成", selection)