I just finished getting through the TArray lecture when I tried to run the code form the method GetTotalMassOfActorsOnPlate. The code compiled just fine but when I stepped on the plate it would cause the editor to crash.
Code used that was causing this issue:
for(auto* Actor : OverlappingActors)
{
UE_LOG(LogTemp, Warning, TEXT("Actor %s is on me, ouch!", *Actor->GetName());
}
My debugging steps
I first tried to limit what was happening in the for loop and even if I did a simple log without any reference to the Actor in the list it would still crash when I stepped on the pressure plate.
I commented out the loop and the editor would now not crash so it had something to do with the loop and the TArray<AActor*>. So next I decided to try and see if there were any elements in the TArray once the PressurePlate->GetOverlappingActors(OUT OverlappingActors) method was called. I added this maco log output:
UE_LOG(LogTemp, Warning, TEXT("I found %d Actors"), OverlappingActors->Num());
Once this compiled this would produce a message every frame but the idea is that now I knew if there were items in the TArray. When nothing was in the TriggerVolume it would produce 0 items in the array which is expected. Once I stepped on the plate it would turn to 1 item in the array. Great we are finally getting somewhere. So I grabbed a chair and tossed into the TriggerVolume and viola now I was getting 2 items in the array while I was standing next to the chair. Once I left the trigger volume it still show 1 item in the array.
When now that I knew there were elements I tried one of my old tricks in programming. Always check for valid data before running a section of code. So here is the updated code I’ve added:
PressurePlate->GetOverlappingActors(OUT OverlappingActors);
if (OverlappingActors.Num() > 0)
{
for (auto* Actor : OverlappingActors)
{
TotalMass += Actor->FindComponentByClass<UPrimitiveComponent>()->GetMass();
}
}
Once I added the data validation check the code stopped crashing the engine. I did try and delete the project build files and directories but this didn’t stopped it from crashing. I hope this will help someone else taking this course who might have run into this same or similar issue.
Happy coding!
-LEde