- Home /
Help with a script.
I've got this health bar that follows the player around, but I'd like to make it stick to the bottom left of the screen instead. Can somebody please help me with this? I'm VERY bad at coding.
Here is the script: using UnityEngine; using System.Collections;
[RequireComponent(typeof(PlayerStatController))]
public class PlayerInfoBar : MonoBehaviour
{
public Vector3 offset = new Vector3(0, 2.5f, 0); // Offset for the health bar position relative to object position
public float barWidth = 100;
private Rect _barRect;
private Vector3 _worldPosition = new Vector3(); // Transform position + offset position
private Vector3 _screenPosition = new Vector3(); // Screen position for drawing health bar
private bool _visible = false; // Health bar is visible or not
private PlayerStatController _playerStatController; // Reference to Player Stat script
private Transform _t; // Reference to object transform
private Color _barColor = Color.cyan; // Used by the Infobar
public Color BarColor
{
get { return _barColor; }
set { _barColor = value; }
}
void Start()
{
_t = transform;
_playerStatController = GetComponent<PlayerStatController>();
}
void Update()
{
// Set health bar position
_worldPosition = _t.position + offset;
// Check to see if health bar is within the camera's view
Vector3 viewPoint = Camera.main.WorldToViewportPoint(_worldPosition);
_visible = (viewPoint.x >= 0 && viewPoint.x <= 1 && viewPoint.y >= 0 && viewPoint.y <= 1 && viewPoint.z >= 0);
if(_visible)
{
// Update screen position for drawing the health bar
_screenPosition = Camera.main.WorldToScreenPoint(_worldPosition);
float x = _screenPosition.x - barWidth / 2f;
float y = Screen.height - _screenPosition.y;
_barRect = new Rect(x, y, barWidth, 20);
}
}
void OnGUI()
{
// Draw the health bar if we can see it
if(_visible)
{
GUI.color = _barColor;
GUI.HorizontalScrollbar(_barRect, 0, _playerStatController.health, 0, _playerStatController.maxHealth); // Displays a healthbar
GUI.color = Color.white;
GUI.contentColor = Color.white;
GUI.Label(_barRect, _playerStatController.health + "/" + _playerStatController.maxHealth); // Displays health in text format
}
}
}
Thanks for the help!
I honestly don't know how to transfer all of the references and stuff. This isn't even my bit of coding, someone else made it and I'm trying to adapt it so it can fit my game. Would there be a way to make it stick in one place when it's not GUITexture? Or do I have to do it all in GUITexture?
Your answer

Follow this Question
Related Questions
Center GUIContent and texture for a GUI.Box 1 Answer
Alpha Gradient UI 1 Answer
Health Bar Arc 1 Answer
How to make a health bar in Unity 5? 0 Answers
Getting error CS0120 1 Answer