简体   繁体   中英

Enemy health bar and taking damage

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM