Covert ints to strings (for animation names)

Godot Version 4.1

I’m have an int variable that increases every time a button a pressed, and I have animations that are named “1”, “2”, “3”, etc, and so I basically want it to work like this:

if Input.is_action_just_pressed(“ui_accept”):
$AnimatedSprite2D.play(var_int)

so that it will play the corresponding animation to the value of the variable

You can do this with to_int()

var my_string = "42"
var my_int = my_string.to_int()

You can error check with is_valid_int() like this:

var my_string = "42"
if my_string.is_valid_int():
    var my_int = my_string.to_int()
else:
    print("Invalid integer string")

In the docs:

1 Like

It doesn’t seem to work
here is my code

extends AnimatedSprite2D


var anim = "0"








# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	var animationScene = anim.to_int()
	if Input.is_action_just_pressed("ui_accept"):
		animationScene = (animationScene + 1)
	$".".play(anim)
	
	if Input.is_action_just_pressed("ui_up"):
		get_tree().quit()

I got to work, here is the code:

extends AnimatedSprite2D

var animationScene = 0

func _process(delta):
	var ANIMATION = str(animationScene)
	if Input.is_action_just_pressed("ui_accept"):
		animationScene = (animationScene + 1)
	$".".play(ANIMATION)
	
	if Input.is_action_just_pressed("ui_up"):
		get_tree().quit()

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.