How to change icon by script

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

I wanted a button to change its icon by pressing it. The script was this

extends Node2D

var icon2 = preload(“res://10.png”)
var icon3 = preload(“res://19.png”)
var icon4 = preload(“res://28.png”)
var icon5 = preload(“res://37.png”)

fun _ready():

func _on_Button3_pressed():

However I can’t think what to type on "func _on_Button3_pressed(): "
could you please tell me what to put ?

func on_Button3_pressed():

Wakatta | 2021-03-17 23:08

:bust_in_silhouette: Reply From: Gamemap
extends Node2D
   var icon2 = preload("res://10.png")`
   var icon3 = preload("res://19.png")
   var icon4 = preload("res://28.png")
   var icon5 = preload("res://37.png")

   var counter = 0

   fun _ready():

   func onButton3_pressed(): 
          if counter >= 5: #max. picture number
              counter += 1 
             counter = 2 # first picture number
       $TextureButton.texture_normal = icon+str(counter) #counter as a string 

Maybe you’ll need also .texture_pressed and .texture_hover.

If you want this random you should use randi_range(FROM, TO) instead of counter.

Here is the TextureButton documentation.
Here is the Random Number Generation documentation.

I did it like you said. But after I typed it an error occurred, telling ‘misplaced: else’
What should I do?

Radgrid728 | 2021-03-18 11:37

The else: must be placed exactly below the if. Use only Tab (no spaces)

func test():
Tab if ... :
Tab Tab pass
Tab else:
Tab Tab pass

For Tab use the Key wih two arrows (2nd Key under Esc).

Gamemap | 2021-03-18 12:12