How can i add animations to AnimationPlayer by GDScript?

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

I want to add animations to the AnimationPlayer node dynamically with gdscript.but it didn’t work.
There are some gdscript demos?

What did you try?

exuin | 2023-03-02 17:54

This is my code:

   var library : AnimationLibrary = get_animation_library("")

var anim : Animation
var track : int
var frame_time : float 
for anim_name in ["idle","run"]:
	anim = library.get_animation(anim_name)
	
	if anim == null:
		anim = Animation.new()
		library.add_animation(anim_name,anim)
		
	track = anim.add_track(Animation.TYPE_ANIMATION)
	#anim.track_set_path(track,sprite.get_frame_property_path())
	anim.track_set_path(track,"AnimatorSprites/BodyBase:frame")
	
	frame_time = 0.1
	var time = (- frame_time)
	var frames : Array = [0,1,2,3,4,5]
	for frame in frames:
		time += frame_time
		anim.track_insert_key(track,time,frame)
	
	anim.set_length( frame_time *  frames.size())
	
	#anim.value_track_set_update_mode(track,Animation.UPDATE_DISCRETE)
	#anim.track_set_interpolation_type(track,Animation.INTERPOLATION_LINEAR)
	#print(has_animation(anim_name))

This is my node tree:
AnimationPlayer
AnimatorSprites (Node2d)
----BodyBase(Sptite2d)

eastry | 2023-03-03 00:09

I’ve also been trying unsuccessfully to add animations at runtime in GDScript. Everything seems ok but when I run them, weird things happen. One thing you may also want to do tho is set the animation track name

aidave | 2023-03-05 17:51

Thanks,it worked,when i changed the animation track name to TrackType.TYPE_VALUE.

eastry | 2023-03-06 03:56