Random image loading?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Azimuth7
:warning: Old Version Published before Godot 3 was released.

Hi ! I´m pretty new to this game engine and I´m trying to do a very simple procedure…
I created two buttons (texture buttons) and they are big like deck cards.
I´m struggling trying to do a procedure like, when someone press the button the Godot will pick a random image from my loaded images and load as the image texture of the pressed button.
Are there any way to do this? Or should I try a different approach?

Thank you in advance

You can store/preload the images first in a constant like this:

const images = [preload("res://image1.png"),
                preload("res://image2.png"),
                preload("res://image3.png")]

Then, in a function that will be called when the button is pressed, just add this:

func _onButtonPressed():
    set_texture(images[round(rand_range(0,2))])

The rand_range() method will choose a float from zero to two, so we must round it to the nearest integer. However, the rand_range method will always choose the same random number, so you can use the randomize() method before the true random number (someone said like that) but I don’t know how to use it :v

tam0705 | 2017-06-28 02:02

Super thanks!

Azimuth7 | 2017-06-29 22:06

:bust_in_silhouette: Reply From: Zylann

You can do what tam0705 said to get the list of texture you can potentially display, and then set it on your TextureButton using button.set_pressed_texture(tex). Take a look at the doc for changing other states of the button: TextureButton — Godot Engine (latest) documentation in English

Thank you very much…

Azimuth7 | 2017-06-29 22:06

:bust_in_silhouette: Reply From: Azimuth7

Now I´ve came accross a different problem, it´s giving me an invalid call on function get_pressed_ texture… :frowning: