export variable (NodePath) Not found when node is instanced

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

I’m trying out scriptable objects in Godot and I ran into an issue with an export variable that is of type NodePath.

My object

  export (NodePath) var rayCast
  export (NodePath) var animatedSprite

  onready var ray = $rayCast
  onready var anim = $animatedSprite

In the editor
I create my player scene with my scriptable object as the root node:

I select my nodes:

Next I instance my player scene in the MainScene

But when I press run:
I get the error :

E 0:00:00.498 get_node: Node not found: animatedSprite.
<C++ Error> Condition “!node” is true. Returned: __null
<C++ Source> scene/main/node.cpp:1381 @ get_node()
Character2D.gd:22 @ _ready()

Do I get this error because my animatedSprite NodePath no longer finds the node?

please show your _ready method

whiteshampoo | 2021-03-28 17:18

:bust_in_silhouette: Reply From: Wakatta

When a node is initialized it’s global variables are set first. In the example you provided since $rayCast and $animatedSprite are not part of the sceneTree this error is thrown when you try to get their nodes.

When referencing a node using get_node which is what $ does, the referenced name must be exactly as seen in the sceneTree like this

onready var ray = $RayCast2D
onready var anim = $PlayerSprite

And if it’s not yet part of the sceneTree use var instead of onready var