How to create an Anim Instance in C++?

Hey everyone!

As the question says, how do you create a c++ class derived from Anim Instance properly? Now I don’t mean how to create the class itself (I know how to do that). I mean, what is the bare necessity code that I need to get it to compile so that I can create an Animation Blueprint derived from my custom anim instance, in the Editor?

I followed both of Rama’s tutorials on the subject here and here, but whenever I try to create an Animation Blueprint derived from my custom anim instance the editor instantly crashes. The code compiles with no warnings or errors though. And this also happens when trying to reparent an Animation Blueprint to my custom anim instance.

So if anyone knows how to properly code it I would be very grateful to learn.

Here is my code

// .h file

#pragma once

#include "Animation/AnimInstance.h"
#include "MyAnimInstance.generate.h"

UCLASS(transient, Blueprintable, hideCategories=AnimInstance, BlueprintType_
class MYPROJECT_API UMyAniminstance : public UAnimInstance
{
     GENERATED_BODY()

public:

     virtual void NativeInitializeAnimation() override;

     virtual void NativeUpdateAnimation(float DeltaTimeX) override;

     APawn* OwningPawn;

     UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Movement")
     float Speed;

};

here’s the .cpp

#include "MyProject.h"
#include "MyAnimInstance.h"

void URayAnimInstance::NativeInitializeAnimation()
{
     Super::NativeInitializeAnimation();

     OwningPawn = TryGetPawnOwner();
}

void UMyAnimInstance::NativeUpdateAnimation(float DeltaTimeX)
{
     Speed = OwningPawn->GetVelocity().Size();
}

What am I missing?

1 Like

in the .h I meant to type a “)” at the end of the UCLASS line, not a “_” That’s just a typo and not my actual code.

Ugh and I meant to type “void UMyAnimInstance::NativeInitializeAnimation()” on line 4 of the .cpp. Sorry for the typos. I don’t know how to edit questions after they’ve been asked.

I forgot about this question. I had eventually figured it out, and it is as the above person said; you need to do a check to make sure the variable is valid before trying to do anything with it, otherwise it won’t like you code. Thanks JinRiGuang for answering!

When I add Check code for OwningPawn, It’s not crash again.

if (OwningPawn)
{
	Speed = OwningPawn->GetVelocity().Size();
}