Godot Version
v4.5.dev5.official [64b09905c]
Question
Hi,
New to Godot Engine, it all seems nice!
I have below script linked to Node2D in a new scene.
Runs without errors, but the sprite is not shown on the screen?
What could be wrong?
SS
extends Node2D
func _initialize():
var sprite_node = Sprite2D.new()
sprite_node.texture = load("res://assets/images/BG_Black.png")
sprite_node.global_position = Vector2(100, 100)
get_tree().root.add_child(sprite_node)
Hi,
I guess you’re calling that function on ready? In that case, that would explain the issue, as adding children to scene root on ready doesn’t work as you would expect (I believe this is due to the tree being busy setting up stuff, but I’ll let anyone give a better explanation as I’m not an expert on that topic
).
If you add the sprite to the Node2D itself, like this:
func _initialize():
var sprite_node = Sprite2D.new()
sprite_node.texture = load("res://assets/images/BG_Black.png")
sprite_node.global_position = Vector2(300, 300)
add_child(sprite_node)
It should work (at least it does on my side).
And if you really need to add a child to the root, you can probably wait for it to be initialized, by deferring the add_child call.
Hi,
I tried your code, still no sprite shown when run?
Completely new to Godot Engine, but have some JavaScript programming knowledge.
Any ideas about what I am doing wrong?
The script is attached to the Node2D in the scene.
SS
Try doing it on _ready()
:
func _ready():
var sprite_node = Sprite2D.new()
sprite_node.texture = load("res://assets/images/BG_Black.png")
sprite_node.global_position = Vector2(300, 300)
add_child(sprite_node)
1 Like
Hi,
Thank you! The sprite now displays!
SS
1 Like