Randomly choose animation

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

Hi everyone,

there are two animations ready in my AnimationPlayer: Anim1 and Anim2.

Now I’d like one of them to be played randomly (after some random time). And then the whole thing should start over again.

This is my code:

func _ready():
	randomize()
	var t = rand_range(3,10)
	yield(get_tree().create_timer(t),"timeout")
		
	var anims = [$AnimationPlayer.play("Anim1"), $AnimationPlayer.play("Anim2")]
	return anims[randi() % anims.size()]

	_ready()

It appears that only the currently (in the AnimationPlayer) selected animation is being played (be it Anim1 or Anim2), and only once. Why doesn’t _ready() start over again, what am I missing?

EDIT:
Correction: I believe it doesn’t matter which animation is being selected in the AnimationPlayer.

:bust_in_silhouette: Reply From: Wakatta

Firstly

# in this line return ends execution of the function and exits
return anims[randi() % anims.size()]

# meaning anything after that line never gets executed
# like this one
_ready()

Secondly

# in this line the array will be filled with the function's return statement
# which is void in this case so most likely [null, null]
var anims = [$AnimationPlayer.play("Anim1"), $AnimationPlayer.play("Anim2")]

To create a loop of this kind the signal animation_finished in AnimationPlayer may be your best bet

func _ready():
    randomize()
    on_animtion_finished("Anim1")

func on_animtion_finished(anim):
    var anims = $AnimationPlayer.get_animation_list()

    # to avoid replaying the last animation
    # anims.erase(anim)

    yield(get_tree().create_timer(rand_range(3,10)), "timeout")
    $AnimationPlayer.play(anims[randi() % anims.size()])

Thanks for your thorough explanations. I was sceptical, but still the return in this post fooled me: https://forum.godotengine.org/24190/how-can-i-choose-between-two-numbers-randomly
Spot on with your second suggestion as well, null returned indeed. I did not know get_animation_list yet, which saved the day. Everything runs just fine now, thank you!

pferft | 2023-02-15 21:39