How can I execute code before engine start?

I need to add some code execution in C++ before engine starts. Like:

  1. Database connections.
  2. init functions for my classes
  3. And rest…

Is there any startup point/delegate/class in unreal engine like main C++ function?

Currently I’m using Unreal Engine 5.2.

The earliest time you can execute code is at CRT initialization, which is basically the initialization of top-level static variables. It happens even before Main or DllMain.

In a monolithic (shipping) build you have a single executable so the CRT init happens (including project code) before Main. None of the engine framework will be available at this point though.

  • You can bind the FCoreDelegate::OnInit delegate to get a callback when the engine is initializing, and you may have access to a few more things (don’t know the specifics).
  • You can declare your own Game module subclass and override StartupModule, to execute code when your module is loaded (meaning all engine modules and project dependent modules are already loaded)
  • You can bind the FCoreDelegate::OnPostEngineInit delegate to get a callback slightly after (don’t know the specifics, probably all modules are loaded)

In modular build (editor, built with DLLs) your project’s DLL is loaded much later (at the time StartupModule is called) and there is no way to execute code beforehand. Also afaik you cannot use the OnInit delegate since your game module is loaded after its trigger.
If you want to execute code earlier in a modular build, you might have to make an engine-level plugin.

When you create a C++ project, the bootstrapper automatically creates the ProjectName.cpp file that registers your game module. You can start here, and see what fits you best.

#include "ProjectName.h"
#include "Modules/ModuleManager.h"

void LogTimestamp(const FString& Tag)
{
    // log for non-shipping
    UE_LOG(LogTemp, Log, TEXT("@@@@@ %s: %s @@@@@"), *Tag, *FDateTime::Now().ToIso8601());
    // write to file for shipping
    FFileHelper::SaveStringToFile(FDateTime::Now().ToIso8601(), *FPaths::Combine(FPaths::ProjectDir(), Tag+".log"));
}

class FMyGameModule : public FDefaultGameModuleImpl
{
    virtual void StartupModule() override
    {
        LogTimestamp("StartupModule");
    }
};

IMPLEMENT_PRIMARY_GAME_MODULE(FMyGameModule, ProjectName, "ProjectName");

bool CrtInit()
{
    LogTimestamp("CrtInit");

    FCoreDelegates::OnInit.AddLambda([]() {
        LogTimestamp("OnInit");
    });
    FCoreDelegates::OnPostEngineInit.AddLambda([]() {
        LogTimestamp("OnPostEngineInit");
    });
    return true;
}
static bool init = CrtInit();
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.