Events for tracking when single objects enters/leaves Selection

I’m designing a plugin that’ll facilitate the place building process on Roblox. This plugin is to interact with Studio’s Selection service. This is the code I implemented to account for individual additions and removals:

function addSel(p)
	--Code your desires here.
end

function removeSel(p)
	--Code your desires here.
end

local studioSels={}
game.Selection.SelectionChanged:connect(function()
	local logs={}
	local old=studioSels
	studioSels=game.Selection:Get()
	for i,p1 in next,studioSels do
		local b='add' 
		for I,p2 in next,old do
			if p1==p2 then
				b='keep'
				break
			end
		end
		logs[p1]=b
	end
	
	for i,p in next,old do
		if not logs[p] then
			logs[p]='remove'
		end
	end
	
	for p,l in next,logs do
		if l=='remove' then
			addSel(p)
		elseif l=='add' then
			removeSel(p)
		end
	end
end)

Not only done this piece of code iterate over the selection table through a nested loop to check for additions, but it also iterates again just to check for removals. In addition, I had to create a proxy table to keep a log of which elements got added and removed. This is disastrous for builders who rely on intricate details; we have use cases where hundreds or even thousands of parts are selected at a time. I’m also required to evaluate both this code snippet’s efficiency and correctness.

Since Roblox’s Selection API probably works directly with the underlying C++, I believe the Studio team have the capability to implement these events:

game.Selection.SelectionAdded:connect(addSel)
game.Selection.SelectionRemoved:connect(removeSel)

Or if you’re inclined to modify the pre-existing SelectionChanged method:

game.Selection.SelectionChanged:connect(function(addT,remT)
	for i,p in next,addT do
		addSel(p)
	end
	for i,p in next,remT do
		removeSel(p)
	end
end)

or:

game.Selection.SelectionChanged:connect(function(parts)
	for i,p in next,parts.Add do
		addSel(p)
	end
	for i,p in next,parts.Remove do
		removeSel(p)
	end
end)
2 Likes

This topic was automatically closed after 1 minute. New replies are no longer allowed.