Plugin : Initialize protected, persistent object

Hello,

I’m a Games Engineer student and currently developing a plugin. The plugin will be used through a BPFunctionLibrary.
For the plugin I’ll need an object (let’s call it Watcher), that is created on Plugin StartUpModule() and can be accessed by all classes inside my plugin module. It’s supposed to hold values like position, materials etc.

My first idea was to declare it inside my PluginModule.h and use the StartUpModule() method to create an instance of it. Since the StartUpModule() is called once, Watcher would be a Singleton as intended.

#pragma once

#include "ModuleManager.h"
#include "Watcher.h"

class FEasyFootPrintsModule : public IModuleInterface
{
public:
	 UWatcher* watcher;
	 UWatcher* getWatcher() { return watcher; }

	/** IModuleInterface implementation */
	virtual void StartupModule() override;
	virtual void ShutdownModule() override;
};

Inside the cpp:

void FEasyFootPrintsModule::StartupModule()
{
	watcher = NewObject<UWatcher>();
}

Inside my functions of the BPFunctionLibrary.cpp I’d like to have access to the Watcher object to define different behaviour based on the values inside Watcher. Since Watcher is a member variable of my PluginModule, I need a reference to it. Where do I get it?

Or is there a better solution?

First of all insted of UWatcher* use WeakObjectPtr<UWatcher> or else you risking invalid pointer, also read here how to keep this object alive and prevent it from garbage collection:

As main issue, you eather need to get module class object form module manager:

Or create singleton in your module class so you can direcly refrence it, you cna look up in other modules in engine to see how it works, here example of HTTP:

https://github.com/EpicGames/UnrealEngine/blob/76085d1106078d8988e4404391428252ba1eb9a7/Engine/Source/Runtime/Online/HTTP/Private/HttpModule.cpp

https://github.com/EpicGames/UnrealEngine/blob/76085d1106078d8988e4404391428252ba1eb9a7/Engine/Source/Runtime/Online/HTTP/Public/HttpModule.h

 HTTP_API static FHttpModule& Get();

/** singleton for the module while loaded and available */
static FHttpModule* Singleton;

and in CPP

FHttpModule& FHttpModule::Get()
{
	if (Singleton == NULL)
	{
		check(IsInGameThread());
		FModuleManager::LoadModuleChecked<FHttpModule>("HTTP");
	}
	check(Singleton != NULL);
	return *Singleton;
}

I know you plan to do so with UObject, but i’m not sure if that is safe thing to do, so i recomand you to it with module class as most module classes in engine do.

My Solution was a Singleton, accessed through a static method

UWatcher * UWatcher::GetInstance()
{
	static UWatcher* i = 0;
	if (!i) {
		i = NewObject<UWatcher>();
		i->AddToRoot();
	}
	return i;
}