Search Unity

How to make health bar disappear if you don't see enemy?

Discussion in 'Scripting' started by coder2988, May 29, 2015.

  1. coder2988

    coder2988

    Joined:
    May 24, 2015
    Posts:
    4
    I made an enemy health bar script that makes the enemy health bar show up over the enemy's head. I don't know how could I make it so that when I don't see the enemy (have him in my line of sight), the health bar disappears, and then again when I see the enemy the health bar appears again?
    Here's the script. Please help!

    using UnityEngine;
    using System.Collections;

    public class EnemyHealth : MonoBehaviour {
    public int maxHealth = 100;
    public int curHealth = 100;
    public float healthBarLength;

    // Use this for initialization
    void Start () {
    healthBarLength = Screen.width / 2;
    }

    // Update is called once per frame
    void Update () {
    AdjustCurrentHealth (0);
    }

    void OnGUI(){
    Vector3 screenPosition =
    Camera.current.WorldToScreenPoint (transform.position); // Gets screen position
    screenPosition.y = Screen.height - (screenPosition.y + 1); // Inverts Y
    Rect rect = new Rect (screenPosition.x - 50, screenPosition.y - 12, 100, 24); // Makes a rect centered at the player
    GUI.Box (rect, curHealth + "/" + maxHealth);
    // GUI.Box (new Rect (10, 40, healthBarLength, 20), curHealth + "/" + maxHealth);
    }

    public void AdjustCurrentHealth(int adj) {
    curHealth += adj;

    if (curHealth < 0)
    curHealth = 0;

    if (curHealth > maxHealth)
    curHealth = maxHealth;

    healthBarLength = (Screen.width / 2) * (curHealth / (float)maxHealth);
    }
    }
     
  2. WheresMommy

    WheresMommy

    Joined:
    Oct 4, 2012
    Posts:
    890
  3. SubZeroGaming

    SubZeroGaming

    Joined:
    Mar 4, 2013
    Posts:
    1,008
    Just check if the render is visible to the main camera and turn that object off.

    Look at the Render class and find isVisible property.
     
  4. WheresMommy

    WheresMommy

    Joined:
    Oct 4, 2012
    Posts:
    890
    If he is using a first person thing or 3rd person, than this will work. If it is like a top down thing, then he has to tell us as the camera would "see" the object even if the player should not.
     
  5. SubZeroGaming

    SubZeroGaming

    Joined:
    Mar 4, 2013
    Posts:
    1,008
    ah, then when you don't "see" the enemy as you say have him in your line of site,

    a raycast pointing in your forward direction would be a good way to detect it.
     
    WheresMommy likes this.
  6. coder2988

    coder2988

    Joined:
    May 24, 2015
    Posts:
    4
    I use third person, and i want the health bar to show up whenever my main camera sees the enemy gameobject
     
  7. WheresMommy

    WheresMommy

    Joined:
    Oct 4, 2012
    Posts:
    890
    Then you can use SubZeroGamings advice, as this is what you are looking for. If the it is visible to the camera, show it.