// Copyright (c) 2012-2023 Wojciech Figat. All rights reserved.
using System;
using FlaxEditor.Scripting;
using FlaxEngine;
using FlaxEngine.Utilities;
using Object = FlaxEngine.Object;
namespace FlaxEditor.Actions
{
///
/// Implementation of used to add/remove from the .
///
///
[Serializable]
sealed class AddRemoveScript : IUndoAction
{
[Serialize]
private bool _isAdd;
[Serialize]
private Guid _scriptId;
[Serialize]
private Guid _prefabId;
[Serialize]
private Guid _prefabObjectId;
[Serialize]
private string _scriptTypeName;
[Serialize]
private string _scriptData;
[Serialize]
private Guid _parentId;
[Serialize]
private int _orderInParent;
[Serialize]
private bool _enabled;
internal AddRemoveScript(bool isAdd, Script script)
{
_isAdd = isAdd;
_scriptId = script.ID;
_scriptTypeName = script.TypeName;
_prefabId = script.PrefabID;
_prefabObjectId = script.PrefabObjectID;
try
{
_scriptData = FlaxEngine.Json.JsonSerializer.Serialize(script);
}
catch (Exception ex)
{
_scriptData = null;
Debug.LogError("Failed to serialize script data for Undo due to exception");
Debug.LogException(ex);
}
_parentId = script.Actor.ID;
_orderInParent = script.OrderInParent;
_enabled = script.Enabled;
}
internal AddRemoveScript(bool isAdd, Actor parentActor, ScriptType scriptType)
{
_isAdd = isAdd;
_scriptId = Guid.NewGuid();
_scriptTypeName = scriptType.TypeName;
_scriptData = null;
_parentId = parentActor.ID;
_orderInParent = -1;
_enabled = true;
}
///
/// Creates a new added script undo action.
///
/// The new script.
/// The action.
public static AddRemoveScript Added(Script script)
{
if (script == null)
throw new ArgumentNullException(nameof(script));
return new AddRemoveScript(true, script);
}
///
/// Creates a new add script undo action.
///
/// The parent actor.
/// The script type.
/// The action.
public static AddRemoveScript Add(Actor parentActor, ScriptType scriptType)
{
if (parentActor == null)
throw new ArgumentNullException(nameof(parentActor));
if (!scriptType)
throw new ArgumentNullException(nameof(scriptType));
return new AddRemoveScript(true, parentActor, scriptType);
}
///
/// Creates a new remove script undo action.
///
/// The script.
/// The action.
public static AddRemoveScript Remove(Script script)
{
if (script == null)
throw new ArgumentNullException(nameof(script));
return new AddRemoveScript(false, script);
}
///
public string ActionString => _isAdd ? "Add script" : "Remove script";
///
public void Do()
{
if (_isAdd)
DoAdd();
else
DoRemove();
}
///
public void Undo()
{
if (_isAdd)
DoRemove();
else
DoAdd();
}
///
public void Dispose()
{
_scriptTypeName = null;
_scriptData = null;
}
private void DoRemove()
{
// Remove script (it could be removed by sth else, just check it)
var script = Object.Find