How to go through an array of images one after another in GDScript

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

I’m quite new to programming and GDScript and wondering how to do something that I did think would be quite simple, but I’m struggling a bit!

I’ve loaded an array of images and I want it to go through each of these images one after the other each time a button is clicked and replace a sprite texture with that particular image.

Right now I can successfully get the sprite to change to any of the images if I put its array number in e.g. new_texture[0] or new_texture[3] etc, but I would like it to go through each of the images one after the other every time the user clicks the button. (And once it’s got to the last image, go back to the first image again)

What am I missing?

Here is the code:

   extends Node

onready var my_sprite = get_node("/root/Game/Picture/Sprite")
var new_texture = [
    load("res://Art/Picture1.png"),
    load("res://Art/Picture2.png"),
    load("res://Art/Picture3.png"),
    load("res://Art/Picture4.png"),
    load("res://Art/Picture5.png"),
    load("res://Art/Picture6.png")
    ]

func _on_Arrow_pressed() -> void:
    my_sprite.texture = new_texture[0]

Thanks in advance for any help!

:bust_in_silhouette: Reply From: Inces

the very most basic functionality of all programming languages : loops.

for x in new_texture :
      Sprite.texture = x

there is also while loop and custom iterators, for some advanced stuff

:bust_in_silhouette: Reply From: lamelynx

To make your code work you need a variable that counts up on each button click and resets itself when reached the end of the list.

extends Node

onready var my_sprite = get_node("/root/Game/Picture/Sprite")
var new_texture = [
    load("res://Art/Picture1.png"),
    load("res://Art/Picture2.png"),
    load("res://Art/Picture3.png"),
    load("res://Art/Picture4.png"),
    load("res://Art/Picture5.png"),
    load("res://Art/Picture6.png")
    ]

var count = 0

func _on_Arrow_pressed() -> void:
    my_sprite.texture = new_texture[count]
    count = count + 1
    if count == len(new_texture): 
        count = 0