I am making a construction system that is activated by pressing the F key, when the construction mode is deactivated all the selected objects should be deselected, but that does not happen, only some are deactivated, so I was searching in my code the error is in the table.find, since for some reason it does not return the value it should and does not work, I have been racking my brain for 5 hours looking for a solution.
function unSetSelection(obj)
if table.find(selections, obj.Parent) then
table.remove(selections, table.find(selections, obj.Parent))
obj.Selections:Destroy()
else
warn("Objeto no esta enlistado")
end
end
If you see any errors, please let me know and thanks in advance.
local selections = {}
function setSelection(obj) -- inserts the parent of the object into the table, which in all cases is a Model
local mark = Instance.new("SelectionBox", obj)
mark.Name = "Selections"
mark.Color3 = colorSelection[obj.Parent:GetAttribute("type")]
--mark.SurfaceColor3 = Color3.new(1, 1, 1)
mark.LineThickness = 0.025
mark.SurfaceTransparency = 0.75
mark.Adornee = obj
local t = TWEEN:Create(mark, TweenInfo.new(1, Enum.EasingStyle.Linear, Enum.EasingDirection.InOut, -1, true), {["SurfaceTransparency"] = 0.6})
t:Play()
table.insert(selections, obj.Parent)
end
function unSetSelection(obj) -- removes the selected instance from the table
if table.find(selections, obj.Parent) then
table.remove(selections, table.find(selections, obj.Parent))
obj.Selections:Destroy()
else
warn("Object is not listed")
end
end
UIS.InputBegan:Connect(function(key, GameProcessed)
if GameProcessed then return end
if key.KeyCode == Enum.KeyCode.F then
configPlayer:SetAttribute("editorMode", not configPlayer:GetAttribute("editorMode"))
showSelection(nil)
for _, o in selections do
unSetSelection(o.selectionPart)
end
warn("Editor Mode:", configPlayer:GetAttribute("editorMode"))
end
end)
As seen in the script, pressing F should deactivate all selections but instead of doing that the following happens:
When using table.remove() it shifts all the other elements in the array to fill the gap. Which is why in the video it removes the first ok, and then the third (which is now the second element).
You could loop the table backwards, or recursively call unset while the table length is greater than 1.
for i = #selections, 1, -1 do
unsetSelection(selections[i].selectionPart)
end
--or
while #selections > 1 do
unsetSelection(selections[#selections].selectionPart)
end