Reputation: 41
I have added the following script to my enemies for the purpose of having a health bar:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Enemy_Health : MonoBehaviour {
public float health;
public float maxHealth;
public GameObject healthBarUI;
public Slider slider;
private void Start()
{
health = maxHealth;
slider.value = calculateHealth();
}
private void Update()
{
slider.value = calculateHealth();
if (health < maxHealth)
{
healthBarUI.SetActive(true);
}
if (health <= 0)
{
Destroy(gameObject);
}
if (health > maxHealth)
{
health = maxHealth;
}
}
float calculateHealth()
{
return health / maxHealth;
}
}
It is working well. However, my player has a weapon (axe) and I would like when my player attacks using the weapon, the health bar of the enemy decreases.
Upvotes: 1
Views: 1846
Reputation: 485
Add a function that decreases the health of enemy on attack. Something like this:
public void DecreaseHealth(healthamount)
{
health -= healthamount;
}
Call this function in your player script with the exact health you want to decrease on attack.
Upvotes: 0