I have a scene 'DragonSelector' which extends Area2D. The scene has a Sprite2D node called 'DragonSprite'.
DragonSelector.gd
class_name DragonSelector
extends Area2D
@onready var dragon_sprite = $DragonSprite
func _ready():
pass
func _process(delta):
pass
func set_texture(dragon_texture: Texture):
dragon_sprite.Texture = dragon_texture
I want to instantiate this scene in 'Main' scene and set the Texture on 'DragonSprite' in runtime.
Main.gd
class_name Main
extends Node2D
var dragon_selector_scene = preload("res://dragon_selector/dragon_selector.tscn")
func _ready():
var dragon_selector_instance = dragon_selector_scene.instantiate()
var texture = preload("res://dragon/flying_dragon-gold.png")
dragon_selector_instance.set_texture(texture)
add_child(dragon_selector_instance)
dragon_selector_instance.position = Vector2(100, 100)
func _process(delta):
pass
This yields an error: Invalid set index 'Texture' (on base: 'Nil') with value of type 'CompressedTexture2D'. This is associated with the texture assignment line in set_texture:
To validate that the texture is where I think it is, I changed function set_texture to load the texture directly from within DragonSelector.gd:
func set_texture(dragon_texture: Texture):
dragon_sprite.Texture = preload("res://dragon/flying_dragon-gold.png")
#dragon_sprite.Texture = dragon_texture
This works as expected. Apologies for the vague title, I have no idea what to refer this to. Suggestions for correction are welcome. Using godot 4.2.1
The issue is that I was trying to set the texture before I added the dragon_selector to the scene tree:
var texture = preload("res://dragon/flying_dragon-gold.png")
dragon_selector_instance.set_texture(texture)
add_child(dragon_selector_instance)
Inside the dragon_selector script, dragon_sprite is only available after Ready() was executed which only happens after dragon_selector is added. Switching the order solved the issue.