Preload a random .png file

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Godot_Starter

So I have three .png files. The names are Eiche1 ,Eiche2, Eiche3. I want to set one of this .png files to the texture of my sprite. Which one must be random. So I tried this:

var random = RandomNumberGenerator.new()

    func _ready():
        random.randomize()
        var random_number = random.randi_range(1,3)
        #Now comes the line with the error:
        §Sprite.texture = preload("res://Eiche"+str(random_number)+".png")

And I got this error:

Parser Error: expected string constant as ‘preload’ argument.

But I thought the str() Methode would covert the number into a string. So where is my mistack?

Thanks for answers!

:bust_in_silhouette: Reply From: DodoIta

You should probably use the String constructor, but I’m not sure about that.
What I would do is $Sprite.texture = preload("res://Eiche%d.png" % random_number).
This should work fine.

:bust_in_silhouette: Reply From: whiteshampoo

you can’t PREload with varying paths.

As far as i know, this works like this:
preload loads before _ready and just sets your texture, when i reaches the line.


You could use just load, but this might give performance-issues, if you use this often.


OR

you could preload all your textures in an array, and choose randomly one of them


OR (maybe the fastes)

you can create a global array (singelton) and choose it randomly from there. So it has to be (pre)loaded only 1 time.


OR (probably the best, thats what i would do)

export an array of textures:

export (Array, Texture) var textures

This has the huge advantage, that you can just drag&drop you textures into an array in the inspector.