Access Violation on GetComponents

I have a setup where I’m using a class that is inherited from ACharacter. This class keeps track of a raw pointer to an AActor named “otherActor” that is also in the scene. I created an Action Binding for a key press, and when it fires I do the following in the character class:

TArray<UStaticMeshComponent*> staticMeshes;
otherActor->GetComponents<UStaticMeshComponent>(staticMeshes);

This works, and I can perform the action repeatedly without issue. But randomly it will crash on the GetComponents call with an access violation, code c0000005. So clearly I’m trying to access a null pointer, but the actor is still valid in the scene and the mesh is still there.

I do make the following calls, every time, on the single static mesh that I obtain from this GetComponents call

staticMesh->SetCollisionEnabled(ECollisionEnabled::NoCollision);
staticMesh->SetSimulatePhysics(false);
staticMesh->SetWorldLocation(...
staticMesh->SetWorldRotation(...
staticMesh->SetPhysicsLinearVelocity(FVector(0.0f, 0.0f, 0.0f));
staticMesh->SetPhysicsAngularVelocity(FVector(0.0f, 0.0f, 0.0f));
staticMesh->AddImpulse(...

I’ll do that a few dozen times and then inevitably get the access violation, always on GetComponents.

Any thoughts? Or tips on making this more robust?

I’ve been suspecting the garbage collector, since it seems to happen randomly after i’ve been spamming the key a few dozen times. I made the actor a TSharedPtr, and I retrieved the mesh one time and stored that also as a TSharedPtr. Now when it asserts I get the same callstack outlined in this bug report.

Yes, no difference, the assert would still occur on the GetComponents call.

Have you tried with this?

TArray<UStaticMeshComponent*> staticMeshes;
if(otherActor != nullptr)
{
    otherActor->GetComponents<UStaticMeshComponent>(staticMeshes);
}

Ok so the problem is not with otherActor becoming a null pointer, but with the GetComponents function, maybe inside it there is a null pointer. Why you don’t use another function to retrieve the component? For example put a function that returns your desired component inside the actor class.

If you haven’t yet, try debugging with Visual Studio and see exactly what is giving you a null pointer. Just set a break-point at the beginning of the function that is causing problems. I’m not sure what would be getting set to null if the calls work fine but then stop randomly.

To improve the code I would store a pointer to the static mesh and just check it each time you need to call the function, unless there is a reason you need to get components (like doing this for different actors). But first I would want to see what is actually causing the exception.