Using UWidgetComponent, UUserWidget and C++ code

I’ve followed a certain tutorial on youtube (Unreal Engine 4 Tutorial - 3D Health Bar (NPC's) - YouTube) on creating 3d health bars. It worked fine when using blueprints, but now I want to adapt this to my setup, so that every type of enemy will have a health bar.

My setup looks like this:
class AEnemyCharacter → class ATestEnemy → BP_TestEnemy
UUserWidget UW_HealthBar

I’ve made it that in constructor of AEnemyCharacter, every subclass gets UWidgetComponent, and, using ConstructorHelpers, managed to assign UWidgetComponent’s class to be UW_HealthBar.
But now, the problem arises.
With things being that way, I obviously cannot access variables of UW_HealthBar from code. But I cannot use bindings in UW_HealthBar as well, since I can’t see a node that would let me find UWidgetComponent that uses this instance of bar, and then access its’ owner’s variables.

Perhaps I’m missing something very elementary, since I’m not very well-versed in blueprints, but does anyone have any idea how to find a way around this problem?

You should create a class UHealthBarWidget : public UUserWidget in which one you put all the properties you need.
Then in your enemy character class, add a pointer to a UHealthBarWidget.
Make it a UPROPERTY(EditAnywhere) so that you can add your proper health bar widget to the enemy BP in the editor.

Thanks, it worked well enough that now I have a widget on enemy’s BP, and it takes needed values.
But could you clarify how to add it to viewport properly, to that it’s attached to given pawn? Since using CreateWidget and then AddToViewport makes it stationary on player’s viewport.

Do you want it 2D or 3D ?

I’d like it to be 3D, if possible.

The thing is, even if you want your widget to be 3d, you might want it to always face the camera which is easier to do with a 2d widget and update its position in the viewport.
Anyway, for 3D widgets, add a UWidgetComponent to your actor (CreateDefaultSubobject). Then AddWidget(yourHealbarWidget) to your component, and … thats pretty much it.
Use carefully as as the doc says, 3D widgets are experimental.

Hm, the method you described is pretty much what I tried before and failed. What would I have to do if I wanted to do this as a 2D widget and just rotate it?

What do you mean by “Failed” ?
As a 2D widget you won’t be able to rotate it on Z.
Still, update the position of your widget in your tick function, or if you have an event driven system for instance, each time the player position is updated.
FVector2D screenPos; GetWorld()->GetFirstPlayerController()->ProjectWorldLocationToScreen(WorldPos, screenPos);

Where WorldPos is the position of your character in worldspace

By “failed” I mean I managed to get the widget show up and rotate correctly, but couldn’t figure out the way to properly give variables to the widget.