Download

Quick C++ Tip - Overriding your game's StartupModule / ShutdownModule functions

Hey guys,

I just found out a pretty neat little thing that seems kind of obvious in retrospect but should prove useful nonetheless. I was implementing a custom gameplay debugger category and I needed to place some code inside StartupModule and ShutdownModule… except these functions aren’t exposed in the primary game module by default. For every custom module you have to manually create them, but for your main game UE4 does some voodoo magic and it’s there. Turns out however that the secret is hidden in YourGame.cpp (that one file that you never really look at other than to maybe define some trace channel names globally):


IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, YourGame, "YourGame" );

I’ve never paid that line any special attention until now. Turns out FDefaultGameModuleImpl is just a static variable:


/**
 * A default minimal implementation of a module that does nothing at startup and shutdown
 */
class FDefaultModuleImpl
    : public IModuleInterface
{ };


/**
 * Default minimal module class for gameplay modules.  Does nothing at startup and shutdown.
 */
class FDefaultGameModuleImpl
    : public FDefaultModuleImpl
{
    /**
     * Returns true if this module hosts gameplay code
     *
     * @return True for "gameplay modules", or false for engine code modules, plug-ins, etc.
     */
    virtual bool IsGameModule() const override
    {
        return true;
    }
};

This means that in YourGame.h you can just do…


class FYourGameModule: public IModuleInterface
{
public:
    virtual void StartupModule() override;
    virtual void ShutdownModule() override;
    virtual bool IsGameModule() const override
    {
        return true;
    }
};

…and then pass that over in YourGame.cpp


IMPLEMENT_PRIMARY_GAME_MODULE(**FYourGameModule**, Wa, "Wa" );

Now you’re free to implement your own StartupModule, ShutdownModule and all the other fun and exciting module functions. Have fun!