How can I make Unity - Scripting API: PrefabUtility.ConnectGameObjectToPrefab work with Undo?
I’ve tried Undo.RecordObject, but I’v soon noticed, that the PrefabUtility actually destroys the previous GameObject instance in the scene, then instantiates a new one from the prefab and copies the last instance settings.
Is it possible to record undo steps for this?
I’ve also noticed, that the Transform data is overriden on the new instance, although all other properties seem to be handled correctly (meaning, if they are different from the prefab, they won’t be changed, but show up as bold labels instead). Is this a bug or am I not using the feature correctly?
public GameObject target;
public GameObject prefab;
void MyEditorFunction()
{
// Undo.RecordObject(target); // Doesn't work, because target will be destroyed.
// Undo.RegisterFullObjectHierarchyUndo(target); // This even crashes Unity and corrupts the scene file permanently.
// -> Reported in case 936220
PrefabUtility.ConnectGameObjectToPrefab(targets, prefab);
}