Invalid get index 'position' (on base: 'null instance') when instance should exist

Godot Version

v4.2.2.stable.official

Question

Hi everyone, I am new to Godot and I am having some trouble understanding the @onready tag. I am attempting to access the player’s position from one of my enemy scripts. The following code (gdscript) results in the error “Invalid get index ‘position’ (on base: ‘null instance’).”

@onready var player = get_tree().get_first_node_in_group("Player")

func update(delta):
     if (player.position - enemy.position).length() < enemy.searchRange:

I am a bit confused because accessing enemy variables works fine using @onready var enemy = $“…/…”

Thanks in advance!

What @onready does is that it is equivalent to putting the line in _ready ie.

func _ready():
   player = get_tree().get_first_node_in_group("Player")

(Although if my memory serves me right it does get called before the script’s _ready function)

What is happening in your code is that get_tree().get_first_node_in_group("Player") is returning null because the group “Player” is empty when you are calling it, most likely because this line is running before the player gets added to the group.

The reason why @onready var enemy = $“…/…” works is because the node you are setting the variable to already exists when the line is called.

I am going to assume you are adding the player to the group on _ready or another lifecycle method, and would advise you to watch this video by Duroxxigar https://www.youtube.com/watch?v=Rywd4O_hVhM

It does an excellent job at explaining how _ready gets called and in what order and when to use the other lifecycle methods such as _enter_tree()

Hope this helped!

1 Like

This is exactly it, I failed to realize that the player had not been added to the group yet. Thank you for both the help and the video recommendation!