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);
}
}
}
}