johnnyGameStudio’s blog

無能なゲームプログラマのぼやき ぎーくになりたい Twitter: https://twitter.com/JGS_Developer

【UE4】アウトプットログに出力される文字列を取得する

開発環境

UE4.21.2 VisualStudio 2017

手順

  1. FOutputDeviceを継承するクラスを作成する
  2. Serialize関数を作成
  3. 渡された文字列をGLogからデバイス登録をする
  4. アウトプットログに出力される処理を実行する(ログ、コンソールコマンドなど)
  5. 出力し終わったら再びGLogからデバイス登録を解除

実際のコード

※専用のUMGを用意するのがめんどくさいので出力方法をImGUIライブラリを使っている.実際に使う際は適当なクラスなり変数なり用意してほしい

#include "ConsoleActor.h"
#include <imgui.h>

namespace
{
    TArray<FString> strArray;
}

class CONSOLETEST_API FConsoleDevice : public FOutputDevice//手順1
{
public:
    FConsoleDevice()
    {
    }
    //手順2(consoleに吐き出されるlog情報が1行ごとに渡される)
    virtual void Serialize(const TCHAR* Data, ELogVerbosity::Type Verbosity, const class FName& Category, const double Time) override
    {
        strArray.Insert(Data, 0);
    }
    //手順2
    virtual void Serialize(const TCHAR* Data, ELogVerbosity::Type Verbosity, const class FName& Category) override
    {
        strArray.Insert(Data, 0);
    }
};

void AConsoleActor::OutputStr(const FString& str)
{
    FConsoleDevice device;
    GLog->AddOutputDevice(&device);//手順3
    UE_LOG(LogClass, Log, TEXT("output -> %s"), *str);//手順4
    GLog->RemoveOutputDevice(&device);//手順5
}
// Called when the game starts or when spawned
void AConsoleActor::BeginPlay()
{
    Super::BeginPlay();
    OutputStr("AAAAAAAAAAAAAAAAAA");
    OutputStr("BBBBBBBBBBBBBBBBBB");
    OutputStr("CCCCCCCCCCCCCCCCCC");
}

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

    //取得したログのゲーム内への出力方法は各々で考えてください

    ImGui::NewFrame();
    Super::Tick(DeltaTime);
    //setting
    ImGui::SetNextWindowPos(ImVec2(50, 20), ImGuiCond_Always);
    ImGui::SetNextWindowSize(ImVec2(550, 300), ImGuiCond_Always);
    ImGui::SetNextWindowBgAlpha(0.5f);
    bool isVisiableCloseBtn = true;
    //Draw
    if (ImGui::Begin("Console"), isVisiableCloseBtn)
    {
        for (int i = 0; i < strArray.Num(); i++)
        {
            ImGui::Text("%s", TCHAR_TO_ANSI(*mBuffer[i]));
        }
    }
    ImGui::End();
}

結果

image.png