Export player position to txt/csv file

Hi @PhilemonSue,

Maybe something like this would work for you?

#include "FindPlayerPosition.h"
#include "Misc/FileHelper.h"
#include "Misc/Paths.h"

// Sets default values
AFindPlayerPosition::AFindPlayerPosition()
{
    PrimaryActorTick.bCanEverTick = true;
    PrimaryActorTick.TickInterval = 0.5f;  // Set tick interval to half a second
}

// Called when the game starts or when spawned
void AFindPlayerPosition::BeginPlay()
{
    Super::BeginPlay();
}

// Called every frame
void AFindPlayerPosition::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);

    // Get first player pawn location
    FVector MyCharacter = GetWorld()->GetFirstPlayerController()->GetPawn()->GetActorLocation();

    // Screen log player location
    GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Blue, FString::Printf(TEXT("Player Location: %s"), *MyCharacter.ToString()));   

    // Prepare the string that will be written to the file
    FString SaveString = FString::Printf(TEXT("Player Location: %s\n"), *MyCharacter.ToString());

    // Get the file path
    FString SaveDirectory = FPaths::ProjectDir() + TEXT("Data");
    FString FileName = TEXT("PlayerCoordinates.txt");
    FString FilePath = SaveDirectory + "/" + FileName;

    // Ensure the save directory exists
    IPlatformFile& PlatformFile = FPlatformFileManager::Get().GetPlatformFile();
    if (!PlatformFile.DirectoryExists(*SaveDirectory))
    {
        PlatformFile.CreateDirectory(*SaveDirectory);
    }

    // Append the players coordinates to the text file
    FFileHelper::SaveStringToFile(SaveString, *FilePath, FFileHelper::EEncodingOptions::AutoDetect, &IFileManager::Get(), FileWrite::FILEWRITE_Append);
}

Notice the following changes:

  1. I set the tick interval to half a second. Not sure if this will be a problem with other parts of your code.
  2. FFileHelper::SaveStringToFile() is used to write the player’s coords to a file.
  3. FILEWRITE_Append to keep the current data and add new lines below.

It may also be worth adding the current time / data before the player coords.

Hope this helps!