GUI appears even when placed behind an object.

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

All GUI elements appear in front of everything else in the 3D world - it’s like a glass window in front of the camera, where all GUI stuff is rendered, so there’s no chance for some 3D world object to occlude a GUI item. The only alternative is to use a 3D object (a cube, for instance) as your health bar.

EDITED: You can detect when health has changed, and show the health bar during some time. Declare these variables before OnGUI, and modify the OnGUI function as follows:

public float duration = 2f; // time to display health bar
private float endTime = 0f;
private int lastHealth = 100;
 
void OnGUI(){
    if (currentHealth != lastHealth){   // if health changed...
        endTime = Time.time + duration; // set timer to show message 
        lastHealth = currentHealth;     // and update lastHealth
    }
    if (Time.time > endTime) return; // does nothing if time elapsed
    // the code below this point has not changed
    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);
}