So I have a Enemy. I have a enemy script with health and such, and I have a script which deals damage to the enemy, I have a healthbar with fill that is a child of my enemy i wnat it to represent my enemies health so when my enemy takes damage my health bar lowers.
Enemy Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EnemyFollow : MonoBehaviour {
public float speed;
public float ehealth;
private Transform target;
// Use this for initialization
void Start () {
EnemyHealthBar = GetComponent<Image>();
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}
// Update is called once per frame
void Update () {
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
if(Vector2.Distance(transform.position, transform.position) <= 5)
{
Debug.Log("Help");
}
if(ehealth <= 0)
{
Die();
if (HealthBarScript.health < 10)
{
HealthBarScript.health += 0.5f;
}
}
}
public void Die()
{
Destroy(this.gameObject);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Destroy(this.gameObject);
HealthBarScript.health -= 1f;
}
}
}
Script that deals damage to enemy
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Projectile : MonoBehaviour {
private GameObject triggeringEnemy;
private Vector2 target;
public float speed;
public float damage;
// Use this for initialization
void Start () {
target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
// Update is called once per frame
void Update () {
transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);
if(Vector2.Distance(transform.position, target) < 0.1f)
{
Destroy(gameObject);
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Enemy")
{
Destroy(gameObject);
triggeringEnemy = other.gameObject;
triggeringEnemy.GetComponent<EnemyFollow>().ehealth -= damage;
}
}
}