MATLAB: App – changing button state when a uifigure is closed

app

When the user presses a state button, a UIfigure is generated. When the user closes that UIfigure, I want to reset the state of the button. I think I have a syntax error somewhere- any assistance is much appreciated. First is the code for the button press, next is the code for the function.
%T0 Switch on/off recording of script
if app.RecordScriptButton.Value==1
app.RecordScriptButton.BackgroundColor='green';
app.RecordScriptButton.Text='Recording';
app.ScriptContent={'%Paste the following text in the main workspace and press <enter> to run the script.'};
app.ScriptWindow= uifigure('Position',[100 100 420 420],'Name','Script');
set(app.ScriptWindow,'CloseRequestFcn',closeScriptFcn);
app.ScriptTextArea = uitextarea(app.ScriptWindow,'Value', app.ScriptContent,'Position',[10 10 400 400],'FontSize',12,'FontWeight','bold');
else
app.RecordScriptButton.BackgroundColor='red';
app.RecordScriptButton.Text='Record Script';
%Close window and erase the script for next use - use try in case user has already closed window
try
close(app.ScriptWindow);
end
end
%function code, located at start of app code.
function closeScriptFcn(app)
app.RecordScriptButton.Value=0;
app.RecordScriptButton.BackgroundColor='red';
close(app.ScriptWindow);
end

Best Answer

A perfect case for events and listeners. Add a listener for the ObjectBeingDestroyedEvent of the new uifigure.
app.ScriptWindow = uifigure;
addlistener(app.ScriptWindow, 'ObjectBeingDestroyed', @(~,~)disp('hello world'))
Replace the disp statement with setting your button state to the desired.