GameInstance C++ troubles

I’m trying to rewrite CCGToolkit from 100% Blueprints to C++ (as much as possible) and there are some problems I’ve encounter with.

  1. On original project there is an BeginPlay function in CardGameInstance (which derived from GameInstance).
    When I try to override BeginPlay() in CardGameInstance2 (on C++), it says that

CardGameInstance2.h:76:18: error: ‘BeginPlay’ marked ‘override’ but does not override any member functions
[2020.05.31-16.53.27:002][696]CompilerResultsLog: virtual void BeginPlay() override;

So, where should I put code from blueprint BeginPlay? To constructor GameInstance::GameInstance? or GameInstance::Init?

  1. Have some troubles with widgets on c++.
    I have in constructor:


static ConstructorHelpers::FClassFinder<UUserWidget> WidgetUIBPClass(TEXT("/Game/CCGToolkit/Blueprints/Widgets/Menu/Test.Test_C"));
WidgetUIClass = WidgetUIBPClass.Class;


and then in CardGameInstance::ShowMenu I have:



WidgetUI = CreateWidget<UWidgetUI>(this, WidgetUIClass);
if (WidgetUI == nullptr)
{
UE_LOG(LogTemp, Error, TEXT("WidgetUI: EMPTY!"));
return;
}
WidgetUI->AddToViewport();


Everything goes smoothly, without any errors, but I don’t see my Widget on screen.
Of course Test widget derived from my WidgetUI class. WidgetUI contains almost nothing. Should I put some code in here?

What’s the problem? Can I summon Widgets from GameInstance?
I’ve try following:



WidgetUI = CreateWidget<UWidgetUI>(GetWorld(), WidgetUIClass);


and



APlayerController* PlayerController = GetWorld()->GetFirstPlayerController();
WidgetUI = CreateWidget<UWidgetUI>(PlayerController, WidgetUIClass);


same result. Black screen, no Widget is showing.

Use this instead of BeginPlay()


virtual void Init() override;

I have this running from my gamestate class and it works fine:


HudGame = CreateWidget<UHudGame>(GetWorld(), SpawnHudGame);
HudGame->AddToViewport();

It should be possible to spawn form anywhere, as long as GetWorld is using the right world. Is your game instance properly set up in the project settings?

Intentionally keeping widgets in the game instance seems like a bad idea, and I’m not sure how reliable that will be in PIE. The Game Instance is often used as a last-resort place to store a widget when a player can’t be found.

A good place to store widgets and references to widget assets is in the HUD class, and you can properly give them owning players too. This matters a lot in multiplayer for example, so it’s a good habit to get into.