How to play animations by code?

I after a created a Pawn Class and set up movement, I was wondering how to go about applying my animations to each specific direction of movement, such as walking forward(to play forward animation, ect). What functions/code would I be working with to achieve this? Also, how do I reference my animations through code?

Hello ,

Here is a small code snippet. You can try to create the AnimSequence in your character and play it.

Creating of animation:

YourCharacter.h

UAnimSequence *Anim;

class YourCharacter : public ACharacter
{
	...
	
	UAnimSequence *Anim;
	
	...
}

YourCharacter.cpp

...

AMyProject3Character::AMyProject3Character()
{
	...
	
	static ConstructorHelpers::FObjectFinder<UAnimSequence> anim(TEXT("AnimSequence'/Game/Mannequin/Animations/ThirdPersonJump_Start.ThirdPersonJump_Start'"));
	Anim = anim.Object;
	
	...
}

...

Playing animation:

...

bool bLoop = false;
GetMesh()->PlayAnimation(Anim, bLoop);

...

AnimSequence’/Game/Mannequin/Animations/ThirdPersonJump_Start.ThirdPersonJump_Start’ - reference of your AnimSequence from engine.

Hope this helps.

2 Likes

Would I specify/call the play animation function in my MoveForward() function. I want the result to be every time the player walks forward, the respective animation play. Would this be the right way to go about achieveing this?

You’ll want to make your own state machine. A series of booleans called via tick. If you want a better idea of this download the Paper2D C++ module and give that a look at.

I think it has something like UpdateAnimation();. So from there you can get an idea on how to make this work.

OMG, thank you for this. There is zero documentation about doing this in code. The docs say “you can play animations from code” but never actually show how.

Look at the top responses here:

and here:

For playing UAnimSequence in UE5 you have to do the cast:

UAnimationAsset* AnimationAsset = Cast<UAnimationAsset>(AnimSequence);