- Home /
Unit Healthbar moving when player moves.
Hello, I'm working on hovering healthbars for any game object tagged unit. My theory is to GetObjectsWithTag and add to a list. Then on OnGUI have a foreach loop iterating through said list do draw the textures. This works fine on the player and the healthbar stays on them. But anything else labeled with the tag unit moves when the character moves instead of staying on that transform. Any help would be greatly appreciated.
PS: If it helps I'm using a click to move and the camera follows the player i think that's where I'm running int a problem.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GUIManager : MonoBehaviour {
public List<GameObject> Units = new List<GameObject>();
public Texture barOverlay;
public Texture barBG;
public Camera cam;
Vector2 unitPos;
// Use this for initialization
void Start () {
cam = transform.GetComponentInChildren<Camera>();
}
//Draw Bars
void OnGUI()
{
foreach(GameObject unit in Units) {
unitPos = cam.WorldToScreenPoint(unit.transform.position);
//GUI.Box(new Rect(unitPos.x, unitPos.y, hpBarLength, 20), barOverlay);
GUI.DrawTexture(new Rect(unitPos.x, unitPos.y, 100, 15), barOverlay, ScaleMode.StretchToFill);
}
}
// Update is called once per frame
void Update () {
GetUnits();
}
void GetUnits() {
//update list of units in range
foreach(GameObject unit in GameObject.FindGameObjectsWithTag("Unit"))
{
if(!Units.Contains(unit)) {
Units.Add(unit);
}
}
}
}
Answer by SolutionStudios · Aug 04, 2014 at 08:45 AM
Try inverting the y position on line 26 using: screen.height - unitPos.y, instead of just unitPos.y, as WorldToScreenPoint gives a Vector2 with 0,0 as bottom left, but gui has 0,0 as top left
Your answer
Follow this Question
Related Questions
Doubt with GUILayout 0 Answers
How to make gui texture go behind gui text? 1 Answer
Issue with GUITexture width. 1 Answer
Help With Enemy Health bars 3 Answers
Another GUI question. HealthBar 1 Answer