Highlighting and unhighlighting objects

When the player selects an object, parts are created to show the player that that object has been highlighted. The problem is, I want to unhighlight the previously selected parts when the player selects a new object(s).

I thought of adding the selected objects to a table, then destroying the highlights attached to those parts in the table whenever the method is called. However, I would have to define this table whenever a part is selected, thus wiping the table whenever a new part is selected. Meaning I cant destroy the highlights attached to the previously selected parts.

function Module.new(Obj)
    local self = setmetatable({}, Module)
    self.Obj = Obj -- Obj is a table of selected parts
    self.PrevObj = {} 

    return self
end

function Module:Highlight()
    for _, part in pairs(self.Obj) do
        table.insert(self.PrevObj, part) -- Insert selected parts into PrevObj table

        -- Create and weld highlights to parts 
    end
end)
1 Like

Could you only fire Module.new() once and keep a reference to it in your script without the self.Obj = Obj part and renaming self.PrevObj = {} to self.Objects = {}? Then, have :Highlight() accept BaseParts or Models as variables to highlight and add a :Clear() function to clean highlights? Sort of like this:

function Module.new()
	local self = setmetatable({}, Module)
	self.Objects = {}

	return self
end

function Module:Highlight(objects)
	for _, part in ipairs(objects) do
		if part:IsA("BasePart") and not self.Objects[part] then
			local highlight = part:Clone()
			
			-- Create and weld highlights to parts
			
			self.Objects[part] = highlight
		end
	end
end)

function Module:Clear()
	for _, highlight in next, self.Objects do
		highlight:Destroy()
	end
	table.clear(self.Objects)
end