` Hi there ! I’m an absolute beginner and I’m trying to understand why my instantiated scene acts differently if I place the scene before running the game or if it is placed by the player in game.
Here is the script I have for the placement of the instance:
And here is the script in the instance (the block) scene:
@onready var game_manager = %GameManager
func _on_area2d_body_entered(body: Node2D) → void:
if Input.is_action_pressed(“down”):
queue_free()
game_manager.add_point()
If the block scene is placed before the game, it works as intended (the character can ground pound the block, destroy it, and get 1 point). But if the character place the block in game and does the same thing, the game crashes and I get the error "attempt to call function “add_point” in base “null instance” on a null instance.
Do you know why my instantiated scene can’t access my GameManager like a normal scene can ?
That error means that your game_manager variable is not being set to reference your existing GameManager object.
Pretty sure the %GameManager syntax is a scene unique name which only works for a Node created in the same scene. In this case, the GameManager node is not in the Block scene.
When you instantiate the new block during gameplay, either before or after add_child, you would need to assign the game_manager object by including the line instance.game_manager = game_manager. Then that variable won’t be null when the _on_aread2d… code is called.
But that’s really not a good structure; that kind of coding will cause you problems as your project gets larger. Have your block send a signal when it wants to notify the game manager of something, and have the game manager connect to that signal when you create the block. The point being that the Block ideally shouldn’t know about the GameManager.
When you say the block is placed “before the game” you mean it is added to the scene in the editor?
Yes exactly, when I say that the block is placed “before the game” I mean that it is added to the scene in the editor, sorry for the lack of clarity. Thank you so much for your answer, it worked !! I will try to improve the structure tomorrow morning but you helped me improve my understanding of variables. Have a great day !
Making well structured code is a long term effort and the “theoretical perfect” is the enemy of the “actually working” so don’t stress over it. (Many people too focused on doing it “right” never end up finishing. So it’s a balance. )
As you get more used to godot and develop larger projects, it becomes really helpful to understand best practices and why certain practices that are short- term good end up causing trouble in the long run. But don’t let that concern get in the way of making progress on your project.
Edit to add: while i may (or may not) talk a good game about clean code and best practices, most of my code is probably a hot mess too.