Undo is not working (not deleting newly created object)

Hi!

Could anyone help me to understand what’s going on here(take a look at code snippet below)?

private void OnToPointClick(Hole hole)
    {
        if (fromHole != null && hole != null && fromHole != hole) {
            toHole = hole;
            var stickPrefab = AssetDatabase.LoadAssetAtPath<Stick>(StickPrefabPath);
            if (stickPrefab != null) {
                var instance = PrefabUtility.InstantiatePrefab(stickPrefab) as Stick;
                if (instance != null) {
                    Undo.RegisterCreatedObjectUndo(instance, "Create Stick");
                }
            }
        }
    }

The thing is that this code is not Undoing the creation of the object. I suspect it could be somehow related to the PrefabUtility.InstantiatePrefab(stickPrefab) stuff. So why I press undo - nothing happens, however it should delete the object I just created.

Any ideas are welcome!

Thanks in advance!

InstantiatePrefab instantiates the whole game object but then returns only the reference to a script on the instance game object. Then you pass only the reference to this script to RegisterCreatedObjectUndo. If you undo, Unity will only delete the script on the prefab instance, not the whole prefab.

Instead, pass the prefab instance game object to RegisterCreatedObjectUndo (i.e. instance.gameObject) and then Unity will delete the whole instance on undo.

1 Like

Hey Adrian!
Thanks for the help. However it is not working either. From what I am hear from you is that this code should work, but it is not.

private void OnToPointClick(Hole hole)
    {
        if (fromHole != null && hole != null && fromHole != hole) {
            toHole = hole;
            var stickPrefab = AssetDatabase.LoadAssetAtPath<Stick>(StickPrefabPath);
            if (stickPrefab != null) {
                var instance = PrefabUtility.InstantiatePrefab(stickPrefab) as Stick;
                if (instance != null) {
                    Undo.RegisterCreatedObjectUndo(instance.gameobject, "Create Stick");
                }
            }
        }
    }

This works for me.

Note that you have a capitalization error, it’s instance.gameObject not instance.gameobject (note the O/o). Maybe your code didn’t recompile successfully?

Is the Stick script on the root of the prefab? Does the Undo get registered correctly? If you undo, do see some part of the prefab being deleted?

Yeah… I’ve changed code here on site. Everything is fine in actual code.

  • Stick is on the root of prefab - Yes
  • I think so. I see it in Edit → Undo section… However I must say that if I press on it it is not doing anything and is not disappearing…
  • No prefab deleted, no object deleted. The Undo section also is not changed.

I would check on some sample example and try from there.