How to get a Node2D's position when it's initialized in the editor with drag-and-drop

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By AaronWizard

Background: I have a node that extends Node2D that’s meant to have custom position snapping in the 2D scene editor. I use an editor plugin to control how the node is positioned after it’s dragged with the mouse or nudged with the arrow keys. I’m now trying to figure out how to control the node’s position during editing when one is added to the scene by dragging it from the FileSystem window to the 2D scene editor.

I’m trying to get a node’s position when it’s initialized in the editor by drag-and-drop. I’ve tried accessing it in the node’s _ready and in _enter_tree functions (with the node’s script set to tool mode) but these seem to be called before you’ve finally dropped the node into the scene, so those functions always report (0, 0). I’ve also tried using an editor plugin that handles the node’s class, but none of its functions seem to be called when the node is first initialized.

How else may I access the node’s final position on drag-and-drop initialization, if possible?

:bust_in_silhouette: Reply From: Zylann

I would have thought _ready() would have worked in your case, which implies that the editor sets the position of the node AFTER adding it to the tree, which is not ideal and basically prevents what you are trying to do.

You could open an issue on Github to discuss about ways to do this properly, but in the meantime perhaps you could try this:

func _ready():
    if Engine.editor_hint:
        call_deferred("snap")

func snap():
    # Do your positionning here

If this doesn’t work, you might be able to yield to a short timer you create in _ready before snapping, but that seems like a very very very un-ideal solution.

markopolo | 2019-01-11 21:20

Using call_deferred in my node’s _ready function solved my issue. Thank you.

AaronWizard | 2019-01-11 21:49