Why calling method on object with $ works, but with onready variable do not works

Godot Version

4.2

Question

When I try create var by declering body element:
@onready var body: Node2D = $Body
or such a code
@onready var body: Body = $Body
(…) and then in some method:
body.turnByDegree(positionToRotate)

Such a code throws error but when I use $Body directly

$Body.turnByDegree(positionToRotate)

it works, anyone knows why such a situation happens?

Which error messages are displayed?

1 Like

So the error is:
Invalid call. Nonexistent functon ‘x’ in base ‘Nil’.

obraz

Does this also happen with ‘%’ ? And are the nodes inserted dynamically?

Bildschirmfoto 2024-01-01 um 20.58.37

1 Like

If you take out the explicit type and replace it with := does it still throw an error?

Doesn’t seem like a mistyping error but worth a shot.

1 Like

AFAIK you cannot assign $ to @onready. If i recall correctly it actually throws an error.

As to why, i don’t know.

Anyways, if it doesn’t, my common practice is to do something like:

@onready var body :Body :
     set(node):
          body = node
     get:
          return body

and inside _ready I do:
body = $Body or body = %Body

Edit:
The error I’ve mentioned is thrown when doing @export, not @onready.
Anyways, what I’ve mentioned previously could work.
Also, if you’re having problems with $ or % in @onready, do @export and drag and drop dependencies from the inspector.

1 Like

Is the method that throws the error running before _ready does? For example, your snippet wouldn’t work if you used body in _init.

2 Likes

@alex2782 Yes, with % sign I got the same error.

@SofaLinden yeah, the same error when I use :=

@elementbound I thing no, it is used in ready method as showed lower in screenshot.

@naza.duu It sadly didn’t work either…

=============

So in summary I was able to solve the issue, here is solution for my problem, I was calling turnToPosition before add_child and becasue of that ready method was not running before calling method to turn. It was not initialized, I thought I am doing it in line 8, but it initialized after adding as a child.
I move turn method under add_child and now it works fine, thank you very much guys for help :smiley:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.