Make Your First 2D Game. Error "Invalid access to property or key 'position' on a base object of type 'null instance'"

Godot Version:
4.5

Question:
Hello, I’m trying to complete the Your First 2D Game tutorial from the docs, but when I run my game there’s this error code:
“Invalid access to property or key ‘position’ on a base object of type ‘null instance’, line 12”
What is a null instance?

Here’s my main code:


Pls help me!

Hi,

You need to specify the full path to the node, so that would be $Player/StartPosition.

From looking into the tutorial, MobTimer, ScoreTimer, StartTimer and StartPosition should all be children of Main. In your screenshot they are children of Player instead.

Here is the correct scene structure from the documentation

TL;DR: Create a unique name for the node, declare it in the code as a @onready var and it’s done.

So, you are trying to access $StartPosition from the Main node, which is 2 levels above it.

As @sixrobin and @hyvernox mentioned, you need to specify the full path to the node you are trying to access. In this case, $Player/StartPosition.

A better approach is to define it as a @onready variable and access it from your variable, so you make sure that if it changes, you only need to change in the variable declaration.

Another topic and even better approach is to use a unique unique name to the node, so it won’t matter the path of it.

To create the unique name, right click your node and than select “Access as unique name”.

Now, once you drag your node inside your code editor holding cntrl or cmnd, it will automatically use the unique name created. Something like:

@onready var start_position: Node2D = %StartPosition

Always try to use unique names for complex scene composition and also onready declarations.

Echoing what sixrobin and hyvernox have said. Additionally, you can physically drag the node you are trying to reference into the code editor, and it will automatically write the correct path to that node.