Skip to content

Selection ​

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

概览 ​

Selection 是编辑器侧的选择管理服务,负责维护当前被选中的 Unit 集合并对外提供批量的查询与修改能力。它支持读取当前选中列表、整体替换选中集合、向现有选中追加单元以及从选中中移除单元,并在选中集合发生变化时通过 SelectionChanged 事件通知监听方。

Get by:

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

函数 ​

Get ​

获取当前选中项集合,返回一个数组。

返回值

类型说明
Array当前选中项数组;服务节点为服务实例(带该服务自身的容器与属性方法),其余为 Unit

获取当前选中的 Unit 列表

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

Set ​

用传入的 Unit 数组替换当前选中集合。

参数

参数类型说明
unitsArrayUnit 对象 / 服务实例 / unitId 列表

替换当前选中

lua
-- @runtime editor
local selection = editor:GetService("Selection")
local previous = selection:Get()
print("替换前选中数量:", #previous)
selection:Set({})
print("清空后选中数量:", #selection:Get())
selection:Set(previous)
print("恢复后选中数量:", #selection:Get())

Add ​

向当前选中集合追加若干项,参数为要加入选中的 Unit 数组。

参数

参数类型说明
unitsArrayUnit 对象 / 服务实例 / unitId 列

新增单位到当前选中集合

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 ​

从当前选中集合中移除若干项,参数为要移出选中的 Unit 数组。

参数

参数类型说明
unitsArrayUnit 对象 / 服务实例 / unitId 列表

从当前选中中移除指定 Unit

lua
-- @runtime editor
local selection = editor:GetService("Selection")
local previous = selection:Get()
print("移除前选中数量:", #previous)
selection:Remove(previous)
print("移除后选中数量:", #selection:Get())
-- 恢复原有选中,避免影响编辑器后续操作
selection:Set(previous)
print("恢复后选中数量:", #selection:Get())

事件 ​

SelectionChanged ​

签名:SelectionChanged()

当前选中集合发生变化时触发(视口点选 / 大纲树点选 / 框选 / 快捷键清空,以及经 Set / Add / Remove 改变选中)。事件不带参数,只表达「选中变了」,插件需自行调 Selection:Get() 取当前选择。仅在编辑器态有效,且只反映本地用户的选中——协作者操作导致的选中变化不会触发本地插件。多选批量操作只通知最终态;Connect 之前发生的变化不补发。