Problem with undo/redo in plugin

Hello
I am testing a small plugin to convert Model to Folder and vise versa
However after swapping, if I move my model/folder to a different position on the screen and then try to undo before the swap I am getting an error:
“The Parent property of Model is locked, current parent: NULL, new parent Workspace”

I managed the undo/redo as recommended in the reference docs
This is the code of the plugin:

assert(plugin, "This script must be run as a plugin")

local Selection = game:GetService("Selection")
local ChangeHistoryService = game:GetService("ChangeHistoryService")

local toolbar = plugin:CreateToolbar("Swap")
local pluginToolbarButton = toolbar:CreateButton(
	"Swap Folder/Model",
	"Swap between Folder and Model",
	"rbxassetid://13261695695" 
)

local function onClick()
	local selection_list = Selection:Get()
	if #selection_list ~= 1 then warn("Wrong number selected objects!") return end
	
	local recording = ChangeHistoryService:TryBeginRecording("Swap Model/Folder")
	if not recording then
		warn("Error recording undo action for plugin!")
		return
	end
	
	local sel_obj = selection_list[1]
	local newClassName
	if sel_obj.ClassName == "Model" then newClassName = "Folder"
	elseif sel_obj.ClassName == "Folder" then newClassName = "Model"
	else warn("Unexpected selection in plugin!") return end
	
	local newObj = Instance.new(newClassName)
	newObj.Name = sel_obj.Name
	newObj.Parent = sel_obj.Parent
	for _, obj in sel_obj:GetChildren() do
		obj.Parent = newObj
	end
	
	sel_obj:Destroy()
	--Selection:Set({newObj})

	ChangeHistoryService:FinishRecording(recording, Enum.FinishRecordingOperation.Commit)
	pluginToolbarButton:SetActive(false)
end
pluginToolbarButton.Click:Connect(onClick)

local function isSelectionCorrect()
	local selection_list = Selection:Get()
	if #selection_list ~= 1 then return false end
	local sel_obj = selection_list[1]
	if sel_obj.ClassName~="Model" and sel_obj.ClassName~="Folder" then return false end
	return true
end

local function onSelectionChanged()
	pluginToolbarButton.Enabled = isSelectionCorrect()
end
Selection.SelectionChanged:Connect(onSelectionChanged)
onSelectionChanged()

Does anyone have an idea what I am doing wrong?

Thanks in advance

1 Like

consider using ChangeHistoryService:SetWayPoint() to (mayby) fix this issue.

1 Like