Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

UndoRedo

Inherits: Object

Provides a high-level interface for implementing undo and redo operations.

Description

UndoRedo works by registering methods and property changes inside "actions". You can create an action, then provide ways to do and undo this action using function calls and property changes, then commit the action.

When an action is committed, all of the do_* methods will run. If the undo method is used, the undo_* methods will run. If the redo method is used, once again, all of the do_* methods will run.

Here's an example on how to add an action:

var undo_redo = UndoRedo.new()

func do_something():
    pass # Put your code here.

func undo_something():
    pass # Put here the code that reverts what's done by "do_something()".

func _on_my_button_pressed():
    var node = get_node("MyNode2D")
    undo_redo.create_action("Move the node")
    undo_redo.add_do_method(do_something)
    undo_redo.add_undo_method(undo_something)
    undo_redo.add_do_property(node, "position", Vector2(100,100))
    undo_redo.add_undo_property(node, "position", node.position)
    undo_redo.commit_action()

Before calling any of the add_(un)do_* methods, you need to first call create_action. Afterwards you need to call commit_action.

If you don't need to register a method, you can leave add_do_method and add_undo_method out; the same goes for properties. You can also register more than one method/property.

If you are making an EditorPlugin and want to integrate into the editor's undo history, use EditorUndoRedoManager instead.

If you are registering multiple properties/method which depend on one another, be aware that by default undo operation are called in the same order they have been added. Therefore instead of grouping do operation with their undo operations it is better to group do on one side and undo on the other as shown below.

undo_redo.create_action("Add object")

# DO
undo_redo.add_do_method(_create_object)
undo_redo.add_do_method(_add_object_to_singleton)

# UNDO
undo_redo.add_undo_method(_remove_object_from_singleton)
undo_redo.add_undo_method(_destroy_that_object)

undo_redo.commit_action()