Existing scene returns null when $ referenced

Godot Version

4.6.1

Question

Hi all, I’m having trouble with the following code:

@onready var powerFSM = $PowerStates

For whatever reason, this specific variable returns null, even though the name of the node matches and the other onready variables in this script all return proper values. Here is my scene tree:

Does anyone know what could be causing this problem?

for clarification, the script is inside the “Player” node.

Where is located the script with your code ?

Ah thanks

Did you create the code with CTRL + click + drag ?

no, would you be referring to clicking on the node name? I can try that

It still does not work

If you maintain and drag the node in the files this will create :

$node

if you maintain Ctrl in addition this will create:

@onready var node: HBoxContainer = $node

I saw that you didn’t have a “:” try adding it maybe…

I’ve tried that, and still an error. It’s worth mentioning that when i ctrl + click the PowerStates node, the colon autofills to Node even though PowerStates is of custom type StateContainerMachine.

1 Like

Maybe debug with

print($PowerStates)

and

print(powerFSM)

and see what it reply

this is really strange. The output for print says:

this is for both options, but when I check the debugger:

powerFSM is null. What the heck is going on?

wait, hang on. this error is being made in a different script

let me show what I wrote there

this looks like the relevant part of the script. I still dont fully understand, but maybe it has something to do with how the variables are initialized here?

Are you calling _transition_state() somewhere in _enter_tree() or _init()?

@onready get’s called after those afaik.

1 Like

that makes sense. let me check…

Try replace the var powerFSM by

@onready var powerFSM := $PowerStates

the onready var is targetting a var in player named powerFSM so if you don’t want to do the line replacement go in the script of player and try to locate the var

yep, it was because the player (which starts in state idle) immediately begins to fall, so the state is switched before the variable is ready. Thanks for the tip

edit: after switching the initial player state the player now falls for a bit before the game crashes. the powerFSM variable is still initialised as null before the transition occurs, but if im not mistaken, the ready state should have occured by that point… what could be going on?

1 Like