- Home /
How to keep my health bar directly above my player and straight no matter how the player turns?
Health Bar issue: https://i.gyazo.com/cfa5ee306193bdea7649821ea1b63933.gif How can I keep it straight horizontally above my player at all times no matter which direction my player turns? Health Bar Script:
using UnityEngine;
using UnityEngine.UI;
public class StatusIndicator : MonoBehaviour {
[SerializeField]
private RectTransform healthBarRect;
[SerializeField]
//private Text healthText;
void Start()
{
if (healthBarRect == null)
{
Debug.LogError ("StatusIndicator Bar is Missing");
}
//if (healthText == null)
//{
//Debug.LogError("StatusIndicator Bar is Missing");
//}
}
public void SetHealth(int _cur, int _max)
{
float _value = (float)_cur / _max;
healthBarRect.localScale = new Vector3(_value, healthBarRect.localScale.y, healthBarRect.localScale.z);
//healthText.text = _cur + "/" + _max + "HP";
}
}
Answer by superbsumit · Aug 01, 2016 at 11:28 AM
One way to achieve this is to make an empty gameObject as your player, and make the player sprite and health bar as its children. Rotate the player sprite with the script attached on that empty gameObject or as you wish. This way you can achieve the same effect.
Answer by MrReynevan2 · Aug 01, 2016 at 11:05 AM
You can unparent it from Player and add something like
pp = player.transform.position;
healthBar.transform.position.Set(pp.x, pp.y+0.5f, pp.z);
to your Update() function.
How should I assign pp. Also its saying x,y,z don't exist in the current state.
create a public variable player of type GameObject, and in Start() method assign to it the player:
player = GameObject.Find("Player");
Then create another public field called pp of type Vector3 and update it in Update() function.
Also, I might have made a mistake with the Vector3.Set() function. It doesn't seem to work. Ins$$anonymous$$d try:
healthBar.position = new Vector3(pp.x, pp.y+0.5f, pp.z);
Declare healthBar the same way as the player. Do you follow? If you have problems with that I can write the entire code for you later today.
Answer by mrpmorris · Aug 01, 2016 at 11:14 AM
You could draw it in the OnGUI() method of a MonoBehavior
Your answer
Follow this Question
Related Questions
Have an object only visible when input is held down 1 Answer
Need help with dialogue system script 0 Answers
Is there a reason why Unity would be able to read one variable in a script and not another? 1 Answer
After exporting my project from my PC to my laptop the physics of my game work differently. 1 Answer
Left side panel in monodevelop 1 Answer