uproperty variable in blueprint resetting on compile

I have a variable in my c++ code:

// Hud blueprint
UPROPERTY(EditAnywhere)
UUserWidget* HudWidget = nullptr;

Which shows up in my PlayerPawn blueprint but when I select my HUD blueprint for that variable then click Compile on the blueprint the variable resets to ‘none’.

Can you not have a UPROPERTY for a UUserWidget or something? I’m new to ue4 so not sure what’s going on.

What are you trying to do with the HudWidget in your PlayerPawn? The problem is that UUserWidget* HudWidget will be an instance of that HUDWidget, and that instance will only be valid for the length of your game session (maybe shorter depending on what you do with it). If you intend for your player pawn to spawn this widget and add to the view port then you’ll be better off using:

UPROPERTY(EditAnywhere, Category="MyCategory")
TSubclassOf<class UUserWidget> HudWidget = nullptr;

Then, when you want to spawn the hud you can just ask it to Create the widget using that TSubClassOf variable (you can do this in cpp with CreateWidget(GetWorld(), HudWidget) or in blueprints with the CreateWidget node.

If howerver something else has created the Hud and you want to access it from your player, then you want to build in some routine that will either:

  • As the HUD to register itself with the player pawn. You should store this in a private UPROPERTY(Transient) and probably as a TSharedPtr or TWeakObjPtr. Within your pawn class you can then check if the property is valid and if so, take whatever action you want
  • Have some method in your player pawn (or somewhere accessible to player pawn) which will go and find the active HUD. This might be in AMyHUD or UMyGameInstance. This means that whatever spawns the HUD should be responsible for keeping it alive and passing a reference to it around as needed.