0 votes

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. newtexture[0] or newtexture[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!

in Engine by (12 points)

2 Answers

0 votes

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

by (7,743 points)
0 votes

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
by (33 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.