- Home /
The question is answered, right answer was accepted
How to undo removing components in an editor extension?
Hi. I'm trying to create an editor extension which will remove a component from multiple objects & replace it with another. It's all working fairly well, but I want to be able to undo the changes in the editor.
Undoing the addition of the new component is straightforward enough, Undo.AddComponent() does the job. However, there's no Undo.RemoveComponent(), & no other function seems to work. Undo.RecordObject() & Undo.RecordObjects() don't seem to register anything. Undo.RegisterCompletedObjectUndo() does add an event to the undo stack, but when I call it, the components don't reappear & I get an error message for each object saying "Component could not be loaded when loading game object. Cleaning up!".
//Undo.RecordObjects(objects, "Upgrade Text");
for (int i = allTextObjects.Count - 1; i >= 0; i--)
{
Text text = allTextObjects[i];
GameObject target = text.gameObject;
Undo.RegisterCompleteObjectUndo(target, "Remove Text");
//Record text parameters
DestroyImmediate(text);
TextMeshProUGUI newtext = Undo.AddComponent<TextMeshProUGUI>(target);
//Assign text parameters to textmeshpro
}
Am I missing something in the Undo documentation, or is there some other way to achieve this?
I think you want to use Undo.DestroyObjectImmediate. Didn't test it though, but I guess you should use that ins$$anonymous$$d of Object.DestroyImmediate (which is probably what you are using atm)...
No, either of those would destroy the entire object, but I only want to destroy a component attached to the object.
No, they don't :p. They accept Object as parameter, $$anonymous$$onoBehaviour inherrits Object. If you pass a GameObject as a parameter, it destroys the gameobject, if you pass a $$anonymous$$onoBehaviour as a parameter it destroys only the $$anonymous$$onobehaviour (i.e. removes the monobehaviour from the gameobject)...
Same as with Destroy
How do you remove the component currently? I assumed with DestroyImmediate because there is no such function as 'RemoveComponent' as far as I'm aware...
In the docs, it specifically says this
Important: To correctly handle instances where objectToUndo is an instance of a Prefab, PrefabUtility.RecordPrefabInstanceProperty$$anonymous$$odifications must be called after RecordObject.
So basically this means you cannot use Undo.RecordObject by itself, you need to also call`PrefabUtility.RecordPrefabInstanceProperty$$anonymous$$odifications`