Reputation: 839
The following script applies damage to my enemy prefab, but the health bar above it doesn't match with it's current health. Instead of making changes to it's respective health bar, it only makes a change to the first instance of the prefab in the hierarchy window. The enemies will still be destroyed when the correct amount of damage is applied to them, though. Something to note is that the health bar image is a child of the canvas, and the canvas is a child of the main prefab with the script attached to it. How can I fix this?
using UnityEngine;
using System.Collections;
public class EnemyHealth : MonoBehaviour {
private float curHealth = 100f;
private float GunDamage;
private GameObject hb;
private GameObject gd;
private GameObject canvas;
public float maxHealth;
public string gunType;
void Start () {
canvas = GameObject.Find ("HealthCanvas");
hb = GameObject.Find ("HealthBar");
gd = GameObject.Find (gunType);
GunDamage = gd.GetComponent<Shoot> ().bulletDamage;
}
public void SubtractHealth(float howMuch){
curHealth = curHealth - howMuch;
if (curHealth <= 0) {
Destroy (this.gameObject);
}
//Update health bar
hb.GetComponent<RectTransform>().sizeDelta = new Vector2 (hb.GetComponent<RectTransform>().sizeDelta.x - 0.95f / maxHealth * GunDamage , hb.GetComponent<RectTransform>().sizeDelta.y);
Debug.Log (curHealth);
}
}
Upvotes: 0
Views: 443
Reputation: 839
canvas = this.transform.FindChild ("HealthCanvas").gameObject;
hb = canvas.transform.FindChild ("HealthBar").gameObject;
Upvotes: 1