GameInstance and Widget

Hello. I have a Widget with a textblock inside of it. If I use my gamemode and have add to viewport the widget, it shows.

In my GameMode.cpp the code looks like this:
NameClass = Cast(CreateWidget(GetWorld(), NameBPWidget));
NameClass->AddToViewport();

The User widget is added to the viewport whenever I use my gamemode. But if I use a game instance, the user widget does not appear at all.

In my MainGameInstance.cpp the code looks like this:
NameClass = Cast(CreateWidget(GetWorld(), NameBPWidget));
NameClass->AddToViewport();

As you can see the code is the same but with the game instance, the widget does not show.

I have already done these steps and change it into my game instance Project Settings->Maps and Modes->Game Instance->MyGameInstance

Can’t help you without you specifying where in GameInstance you call your code.

That said, GameInstance and GameMode are not the same at all, so your code might be the same, but the classes you’re calling from are very different.
GameInstance is persistent throughout the entire runtime of the game, while GameMode is not. GameMode only exists while the level it is bound to is open, and if you switch levels a new GameMode is created, even if the levels refer to the same GameMode class.

Also, GameInstance is one of the first classes to actually run when pressing play. Whether that’s in editor or standalone. I’m not sure since it’s not really relevant, but GameInstance might actually start existing prior to the viewport. GameInstance definitely starts existing before UWorld does, so if your code runs at the start of GameInstance, it won’t be able to get the world.

You should only use GameInstance for data you want to be persistent. If you want data about your Widget to be persistent, you can save whatever needs to be saved in GameInstance and get the data in your GameMode to draw the Widget.

You should also know that this will work perfectly fine in singleplayer, but will be problematic in multiplayer.

2 Likes

Thank you for your advice. I will try another way around implementing the widget to viewport. Thanks!