This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
+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():
        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!

in Engine by (378 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.


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.

by (1,536 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 (569 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 Frequently asked questions and 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 [email protected] with your username.