Animation Notify State crashes Unreal in preview

NB. This is for version 5.0.0. UE5 version tags don’t seem to be working.

I came across really strange behavior with animation notify states.

In notify tick, I instruct the function to call a getter in another class to retreive a weapon actor.

h
AHandheldWeaponBase* Weapon = nullptr;
bool bWeaponFound = false;

cpp
if (!bWeaponFound)
    {
        AAIBaseCharacter* AICharacter = Cast<AAIBaseCharacter>(MeshComp->GetOwner());
        // crashes here
        Weapon = AICharacter->GetWeapon();  
    }

    if (Weapon)
    {
        Weapon->Swing(MeshComp);
        bWeaponFound = true;
    }

As the weapon spawns on BeginPlay, it doesn’t exist when I am setting the notify state in an animation BP, so the getter function retrieves a nullptr if the weapon has not spawned or a pointer to the weapon object if it has:

h file
AHandheldWeaponBase* AttachedWeapon = nullptr;

cpp
BeginPlay()
{
AttachedWeapon = GetWorld()->SpawnActor<AHandheldWeaponBase>(WeaponClass);
}

AHandheldWeaponBase* AAIBaseCharacter::GetWeapon() 
{
	if (!AttachedWeapon) {return nullptr;}
	else {return AttachedWeapon;}
}

Firstly, it is bizarre that this function seems to be running in the animation preview. I have no idea why this would be the case. Secondly, I also have no idea why this would cause Unreal to crash. The getter either explicitly returns an initialised nullptr or the object itself.

There are ways I could work around this but I wonder if anyone can shed some light.

Cheers.

if it’s crashing on AICharacter->GetWeapon() it’s crashing because AICharacter is invalid, most likely.

I don’t see any reason why an animation notify wouldn’t run in preview… if you were using it for sound or vfx or something, you might want it to run during preview… in this case, probably not. there might be a bool for turning that off, or maybe you should do a check to see if you’re in game or not… but also a check against AICharacter being null would fix.

Thanks for your answer @eblade.

It runs fine at run time so I guess it’s just trying to access objects that only come into existence on BeginPlay. I hadn’t thought about other use cases for the Notify State. If the default case tends to be wanting to test something in preview, then I guess that’s why it runs.

Anyway, if anyone else runs into this problem, I created a bIsActive bool that acts as a gate for all functionality, made it an editable uproperty and just made sure it was false when hooking it up to an animation.