How to get the total number of frames in an AnimatedSprite2D animation? (Godot 4.2, 4.x)
-
Hi! My goal here is to pick a random frame from the frames in an AnimatedSprite2D. Right now there's only two frames, but I want to add more frames later on without having to go back into the code and change numbers around.
Right now, this is the code that works:
sprite.frame = randi_range(0,1)
This is the code I'm trying to get working:
sprite.frame = randi_range(0,sprite.sprite_frames.get_sprite_frames("default"))
(Most likely, I'll have to add a
- 1
to the end of thatrandi_range(0,y)
because it needs to reference the index of frames which starts at0
instead of1
, not the literal amount of frames.I've looked all around forums for an hour and tried a few different ideas, but I can't get anything that doesn't throw an error. Some people say
sprite.frames_get_sprite_frames()
.sprite.sprite_frames().get_sprite_frames()
, and so on and none of it works. Most often it says that.frames
orget_sprite_frames
doesn't exist. Maybe it was in a previous version of Godot 4 or 3? -
I'm not too sure what your error is, so please elaborate if I misunderstood your problem.
It seems like everything would instantly start working if you deleted "sprite." from all of your code. It worked for me.
frame = randi_range(0,sprite_frames.get_frame_count(animation)-1)
Also, remember to change "get_sprite_frames" to "get_frame_count".
Also also, simply typing "animation" gives the current animation that it's using. -
@lemu_kymoh I'll put the exact code I'm using. (I made things less specific for the sake of the original post.)
@onready var sprPlanet : AnimatedSprite2D = $sprPlanet ... func ANIMATION_FRAME(): # choose a frame from sprPlanet ranging from 0 to the number of how many frames there are. sprPlanet.frame = randi_range(0,sprPlanet.sprite_frames.get_frame_count("planet_types") - 1)
Well as it turns out you're right! It worked. I'm not really sure what went wrong with the other tutorials...