+2 votes

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():
        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!

in Engine by (328 points)

2 Answers

+1 vote
Best answer

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.


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.

by (1,448 points)
selected by
0 votes

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.

by (515 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.