godotgdscript

Invoke a function when renaming node?


pretty straight forward Q, How do I invoke a function when the node is renamed?

I thought maybe _set() function would be invoked but it doesn't work for renaming


Solution

  • Setting the name from the editor bypasses _set(). You can use _set() for intercepting when you set the name from code.


    Another option is to connect the "Renamed" signal (all Nodes have it).

    You can connect as early as _init if you want it to happen before whatever code is instancing the Node has a chance to change its name.

    However, this one only triggers if the Node is inside the scene tree.


    And, finally, a way to detect changes of name regardless of how the change happens is to listen for the NOTIFICATION_PATH_CHANGED notification.

    You get NOTIFICATION_PATH_CHANGED in _notification by default, no need to enable it or anything like that.

    It even works when the Node is not in the scene tree, which I find surprising.

    Even more surprising, it does not trigger when adding the Node to the scene tree, or removing it (those would be NOTIFICATION_ENTER_TREE and NOTIFICATION_EXIT_TREE respectively), despite those actions changing the path the node. So I believe NOTIFICATION_PATH_CHANGED is a misnomer, it should be "NOTIFICATION_NAME_CHANGED".

    Addendum: On Godot 4 it was renamed to NOTIFICATION_PATH_RENAMED.