Attempt to call function 'addPoints' in base 'null instance' on a null instance

Godot 4

Question

Why does this not work. I have a GameController node with:
var points = 0
func addPoints():
points += 1
print(“points”)

I then have a collectable node with the following code:
@onready var game_manager = $GameManager

func _on_area_2d_body_entered(body):
if body.name == “Player”:
game_manager.addPoints()
queue_free()

What im trying to do i get it so when the “Player” enters the collision of the collectable, the game manager will add a point to the point variable and print it to the console but when i test it, it gives me the error in the title at game_manager.addPoints(). Any help is apreciated

can you show where you put the player and game manager in scene tree

then change to this:

@onready var game_manager = $"../../GameManager"

The $ follows a path to children, since GameManager is not a child of Player the path is invalid. I would propose to add GameManager as a Autoload, this would allow all scripts to access it’s variables and functions. Your script chages like so:

# var game_manager deleted

func _on_area_2d_body_entered(body):
    if body.name == "Player":
        GameManager.addPoints()
        queue_free()

Did not work. Gave the same error

i dont see Cherry Scene has the script attached, in which node exactly in Cherry Scene you put the script?

Screenshot 2024-05-14 at 2.57.58 PM

then this should work

@onready var game_manager = $"../../../GameManager"

That worked, thank you. What exactly did it do so i know what not to do next time?

it basically route back to SceneOne then with per ../
so your first ../, it back to Cherry Area2D node
the second ../, it back to Cherries Node2D node
the third ../, it back to SceneOne Node node
then GameManager is where the GameManager Node at

this method usually not favourable, because you have to know the list of tree to make it work, you will need to use signal if favourable
or
put the GameManager into a group “game_manager”
then use get_first_node_in_group

var game_manager=get_tree().get_first_node_in_group("game_manager")

to retrieve the game_manager node, so you dont have to route it like that

1 Like