+1 vote

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():
pass

func onButton3_pressed():

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

Godot version v3.2.3stable.official
in Engine by (22 points)
func on_Button3_pressed():
    set_button_icon(icon2)

1 Answer

+1 vote
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():
          pass

   func onButton3_pressed(): 
          if counter >= 5: #max. picture number
              counter += 1 
          else:
             counter = 2 # first picture number

       $TextureButton.texture_normal = icon+str(counter) #counter as a string 
                                                          variable

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.

by (170 points)

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

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).

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 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 webmaster@godotengine.org with your username.