Instantiated scene returns null

Godot Version

4.3

Question

Hi all. I am making my first full game in godot, and have come across a rather unique problem. I am attempting to instantiate and create an instance of a scene using the following code:

	const BULLET = preload("res://bullet.tscn")
	var new_bullet = BULLET.instantiate()
	%aim.add_child(new_bullet)

however, when I do so, I get the following error:

cannot call method "add child" on a null value.

I’ve tried changing version from 4.4.1 to 4.3 and still the same error. I notice that the linter is correctly detecting what errors I add when I try to change the code but gives this sequence the OK, and by all means from what I’ve found this should be the correct method to instantiate a scene. Does anyone have any idea what might be going wrong? Thank you for your time.

The error means that %aim is null.

I take it aim is a scene? How is it instantiated?

%aim is not a scene, it is a node accessible within the scene that calls the second scene. I used a unique name for it, but the full path would be $player/aimpivot/aim .

I found and solved the problem. “%aim” was meant to refer to “Aim”. I didn’t put a capital letter at the start of the word. Now I suppose I have knowledge of one of godot’s most common and worst errors. Thanks godot. Sorry for the trouble @dharhix.

1 Like

Happy you found it. Also, don’t worry, we’ve all done this. XD

1 Like

The easiest way to avoid this error in the future is to click and drag the %Aim node from your Scene tab into your code at the top while holding down the Ctrl key. You’ll end up with something like this:

@onready var aim: Node = %Aim

Doing this will also save you from race conditions. If you were to put your current code inside _physics_process() it could run before your scene is fully created and throw the same error. Using an @onready variable prevents that from happening.

Thanks. I will keep this in mind.

1 Like