Posistion trouble - Health bar above enemy - C#

Hello!
I have tried to make a healthbar stay above a target, but it doesn’t move more then a few pixels insted of what the target actually moves.

For example I have tried something like this:

public Transform This_enemy;

void OnGUI(){
GUI.DrawTexture(new Rect(This_enemy.posistion.x, 50, healthbar_texture_w, healthbar_texture_h),healthbar);
}

I have tried lots of different posistion, but it seems to only move the X-axis that shows in the “building room”. The x,y,z that has a low amount like 1,2,3 in the building room while the GUI should be moving 100,200, 300 pixels to keep on top of the target. Sorry if you can’t understand what I’m trying to say.
Could I be using the wrong posistion ? I tried local as well :frowning:

Extra info:

  • 2D game!
  • C#

Check the API for Rect: Unity - Scripting API: Rect

The x and y positions you’re passing are being given as the left and top positions of the rect, so they don’t relate the the enemy’s position in the scene.

1 Like

Understand! Still not sure how to get access to the correct x,y. Tried to read the manual but I seem to be missing something as I can’t understand where to get the correct value.

This_enemy.posistion.x hmm…

Look into Camera.WorldToScreenPoint()

1 Like

Nice, thanks!
It seems fine if I attacht it to main camera, but what if the object doesn’t have a camera component thought?

If the object doesn’t have a camera attached you could try Camera.main.WorldToScreenPoint() but make sure your camera has the tag of MainCamera

1 Like