I’ve programmed my enemy’s health exactly how I wanted it, the size place, and how it works. However if I place an object in front of it like a wall the enemy’s health still appears on screen even though the enemy isn’t. Can someone please help me make it so that when the enemy is behind an object it doesn’t show its health bar? I’ve already tried viewport instead of world, and that didn’t work.
using UnityEngine;
using System.Collections;
public class EnemyHealth : MonoBehaviour
{
public int maxHealth = 100;
public int currentHealth = 100;
public float healthBarLength;
public Transform target;
private int healthbarwidth = 70;
//public bool isVisible;
void Start()
{
healthBarLength = Screen.width / 2;
}
// Update is called once per frame
void Update()
{
AddjustCurrentHealth(0);
if (currentHealth == 0) {
Destroy(gameObject);
}
}
void OnGUI()
{
Camera cam = Camera.main;
Vector2 screenPos = cam.WorldToScreenPoint(target.position);
GUI.Box(new Rect(screenPos.x - healthbarwidth / 2, Screen.height - screenPos.y - 30, 70, 20), currentHealth + "/" + maxHealth);
}
public void AddjustCurrentHealth(int adj){
currentHealth += adj;
if (currentHealth < 1)
currentHealth = 0;
if (currentHealth > maxHealth)
currentHealth = maxHealth;
if (maxHealth < 1)
maxHealth = 1;
healthBarLength = (Screen.width / 2) * (currentHealth / (float)maxHealth);
}
}