Dynamic scene object can't find it's own nodes

I’m having an issue with setting the texture and editing other properties on nodes in a sprite in a scene object I made.
I do not understand how it goes wrong, but the code does not seem to reference the scene itself, but looks in the node that called the scene to be initialized.

My code is the following:

Main scene, on a button press this happens

func _on_bullet_pressed():
	var bullet = preload("bullet.gd").new()
	$bullets.add_child(bullet)

This is the code in bullet.gd

func _ready():
	$bullet_sprite.texture = preload("res://assets/green.png")

Whenever preload is called, I get the error:
Invalid set index ‘texture’ (on base: ‘null instance’) with value of type ‘CompressedTexture2D’.
And the app crashes.

The errors tab says the following
Node not found: “bullet_sprite” (relative to “/root/Node2D/bullets/@Node2D@2”).

“bullet_sprite” is a Sprite2D node attached to the root of the “bullet” scene.
How do I fix this?

Do you want to instantiate the Bullet-scene?
The code for that would look like this:

var bullet = load("res://bullet.tscn").instantiate()
$bullets.add_child(bullet)
1 Like