How do i load textures from a array?

Godot Version

godot v4.2.2.stable

Question

I have this simple array with some pngs, and a simple way to change between indexes.

the thing is for some reason the sprite 2d is not changing to the current texture and im wondering how do i fix it.

extends Node2D
@onready var paitings = ["res://Artes/unnamed1.png", 
	"res://Artes/unnamed2.png", 
	"res://Artes/unnamed.png", 
	"res://Artes/Y´Y - Amaro Freitas.png"]
	
@onready var paiting = $Sprite2D.texture
var index = 0

func _ready():
	paiting = load(paitings[index])
	print(paitings)
	print(paitings[index])


func _process(_delta):
	paiting = load(paitings[index])
	
func _on_next_pressed():
	if index != len(paitings) - 1:
		index +=1
	else:
		index = 0
	print(index)


func _on_last_pressed():
	if index != 0:
		index -=1
	else:
		index = len(paitings) - 1
	print(index)

It’s not a good idea to load a resource on every frame. Do it only once when the index changes.

1 Like

You would save a lot of processing time if you stored these preloaded. You don’t need to load() them over and over again. preload() only loads a file once and caches it, and checks to see if it’s loaded before pulling it from disk again.

@onready var paitings: Array[Texture2D] = [
	preload("res://Artes/unnamed1.png"), 
	preload("res://Artes/unnamed2.png"), 
	preload("res://Artes/unnamed.png"), 
	preload("res://Artes/Y´Y - Amaro Freitas.png")
]

What are you expecting this code to do? Because right now you are reloading the same image about 60 times a second without caching for no apparent reason. You can remove it.

Then your other code would be:

func _ready():
	paiting = paitings[index]


func _on_next_pressed():
	if index != len(paitings) - 1:
		index +=1
	else:
		index = 0
	paiting = paitings[index]


func _on_last_pressed():
	if index != 0:
		index -=1
	else:
		index = len(paitings) - 1
	paiting = paitings[index]
1 Like

Yes i was wrong about the process, and the loads, i now changed it to preloads, and change only when pressing the buttons. strangely it still doesnt work.

Thank you, i changed it yet it still doesnt seem to work

You need to reassign it to your sprite2d, store this :
@onready var paiting = $Sprite2D
Instead of the texture reference as you override it and reassign directly :
painting.texture = paitings[index]

2 Likes