Sprite's texture doesn't update when changed

Godot Version

4.2.2

Question

I’m new to Godot.
I’m trying to create a puzzle game, for which I need the user to be able to click and spawn a sprite. I want to be able to pass a texture to the sprite when it spawns, so I’m exporting the texture property and setting it from within my main script when the player clicks.

The problem is, when I do this, no texture is visible.
By monitoring the Remote tab of Godot while the game is running, I can confirm that children are added when I click.
But I cannot see the texture.

I’ve created a VERY basic example, with 1 scene called Token and the other Main.

Here’s the code for Token:

extends Area2D

@export var tile_texture: CompressedTexture2D = load("res://icon.svg")

And here’s the code for Main:

extends Node2D

@onready var token_scene = load("res://token.tscn")
@onready var tile_texture = $Token.tile_texture

func _input(event):
	if event is InputEventMouseButton:
		var token = token_scene.instantiate()
		add_child(token)
		token.tile_texture = load("res://icon.svg")
		token.position.x = 100
		token.position.y = 200

I assume I’m exporting the property incorrectly, or setting it incorrectly, or maybe missing some kind of update call to Godot to tell it to re-draw?

From what i can tell, your token-scene is a area2d and not a sprite so how is it supposed to display a texture?

Thanks for the clarification, @herrspaten

I misunderstood how nodes interact, I guess. I had Token as an Area2D with a CollisionShape2D and Sprite2D as children. I see now that Token should be a Sprite2D containing an Area2D containing an CollisionShape2D.

Based on your comment, I removed the script from token.tscn and changed Token’s type to Sprite2D. Now it works. My Main script, for posterity:

extends Node2D

@onready var token_scene = load("res://token.tscn")
@onready var tile_texture = $Token.texture

func _input(event):
	if event is InputEventMouseButton:
		var token = token_scene.instantiate()
		add_child(token)
		token.texture = load("res://icon.svg")
		token.position.x = 200
		token.position.y = 200

Thanks for the explanation!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.