Could someone please point me in the direction of creating a hovering health bar on the enemy . a general direction as to what code or tutorial to check on would be much help.
You can use the method camera.WorldToScreenPoint(enemy.position) to get the position of the enemy in the screen, then you can draw some textures(related to your health bar, of course) in OnGUI and put them in the position you get in this function sum by some constant just to get the correct position considering that the function will probably return the position of the pivot of the enemy in screen coordinates, and the pivot is often in the center of the model.
C# code:
private Transform _enemy;
private Camera _theCamera;
private Renderer _renderer;
public Texture2D healthBar;
public float constant;
public bool displayHealthBar;
void Start () {
_enemy = transform;
_renderer = _enemy.renderer;
_theCamera = GameObject.FindGameObjectWithTag("MainCamera").camera;
displayHealthBar = true;
}
void OnGUI () {
if((displayHealthBar) && (_renderer.isVisible)) { // display just when the bool is true AND if the GameObject is being used to render geometry/shadows.
Vector3 enemyInScreen = _theCamera.WorldToScreenPoint(_enemy.position);
GUI.DrawTexture(new Rect(enemyInScreen.x, enemyInScreen.y + constant, healthBar.width, healthBar.height), healthBar);
}
}
To get a better visual, you can make some equation, so the ‘constant’ variable vary according to the distance of the enemy to the camera, but that’s up to you.