Casting to MyCharacter in multiplayer getting wrong character, randomly.

I am creating a simple health progress bar in UMG that displays my characters health. In UMG I am casting to MyCharacter and am receiving the health variable but, half of the time it gives me the 2nd MyCharacter’s health (I am running dedicated server, 2 players). I figure I am casting wrong because of multiplayer? When I stored the health variable in the player controller it didn’t help either though. I am also using a local health variable (no replication) and not using my actual health variable which is replicated to display the health to the enemy player (in text though, because UMG won’t display the correct health).

So my question is, am I casting in muliplayer wrong, am I handling my character in multiplayer wrong, or is this a bug?

Creating the widget in MyCharacter_BP

Applying damage, just in case it is relevant.

69947-ue4_setthelocalhealth.png

Setting the local health variable to the replicated health variable, in MyCharacter_BP

Getting all actors of class, looping, getting health and dividing by max health.

You’re creating the widget on the playerBP. This is an issue because each player will have more than one instance of the widget, because one instance of the player is created for every client and one for the server. Create the widget in the player controller. Only one controller per player exists, hence only one widget is made.

But the larger problem is you’ve bound the HP bar value to be set by looping through every player. And only the final value will ever be set. e.g, if player one has 20 hp, and player 2 has 55 hp, the value will ALWAYS get set to player 2. Frankly, I’m shocked you said “sometimes” the values are incorrect - with your setup they should always be wrong. But, luckily this issue also has a simple solution.

You have two options:

  1. Keep the HP stored on the playerBP, and only bind the widget to THAT player, not all.
  2. Store the HP in the playerController, and bind the widget to that.

Thank you so much for the response! I did as you suggested and you explained it so well why it was not working, now I understand foreachloop much better. I wish I could give you reddit gold, haha. Everything is working as expected now, thanks a lot!