Hello, I am new to Unity so I've been using several tutorials to try different things
I used the Health Bar tutorial of http://www.burgzergarcade.com/hack-slash-rpg-unity3d-game-engine-tutorial and made some modifications to create mine.
And I want to know: is it possible to make a GUI.Box Rectangle follow a character's position so that it hovers above its head?
I tried using the ObjectLabel script http://www.unifycommunity.com/wiki/index.php?title=ObjectLabel
but this only works for GUI Text/Textures
I think it could be done if I modify the z position of the rectangle to follow the camera but I have tried several things and I can't make it work.
EDIT: I added the corrected script to help if someone had the same problem as me:
using UnityEngine; using System.Collections;
public class PlayerHealth : MonoBehaviour {
public int maxHealth = 100;
public int curHealth = 100;
public float healthBarLength;
/*public int healthBarWidth;
public int healthBarHeight;*/
public GUISkin healthBarSkin;
public Vector3 screenPosition;
// Use this for initialization
void Start () {
healthBarLength = Screen.width / 8;
}
// Update is called once per frame
void Update () {
screenPosition = Camera.main.WorldToScreenPoint(transform.position);
screenPosition.y = Screen.height - screenPosition.y;
AddjustCurrentHealth(0);
}
private bool _mouseEnter = false;
void OnGUI() {
if(!_mouseEnter) return;
//draw your GUI stuff here with Unity's OnGUI code - see ref for details
GUI.skin = healthBarSkin;
GUI.Label(new Rect(screenPosition.x - 36, screenPosition.y - 35, Screen.width / 8, 7), "Health");
GUI.Box(new Rect(screenPosition.x - 36, screenPosition.y - 35, healthBarLength, 7), "Health");
}
void OnMouseEnter()
{
_mouseEnter = true;
}
void OnMouseExit()
{
_mouseEnter = false;
}
public void AddjustCurrentHealth(int adj) {
curHealth += adj;
if(curHealth <= 0)
Destroy(gameObject);
if(curHealth > maxHealth)
curHealth = maxHealth;
if(maxHealth < 1)
maxHealth = 1;
healthBarLength = (Screen.width / 8) * (curHealth / (float)maxHealth);
}}