TopDownShooter Tutorial in UNITY. PART 04 – health system.

Hello new episode of tutorial series is available under this link:

https://youtu.be/n9GkXRBet2I

Code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class HealthSystem : MonoBehaviour
{
    public float maxHealth = 10;
    float currentHealth;

    public Image mask;
    // Start is called before the first frame update

    void Start()
    {
        currentHealth = maxHealth;
    }

    public void TakeDamage(float _damage)
    {
        currentHealth -= _damage;
        UpdateHealthBar();
        if (currentHealth <= 0)
        {
            Die();
        }
    }

    public void UpdateHealthBar()
    {
        float fill = currentHealth / maxHealth;
        mask.fillAmount = fill;
        if (currentHealth < 0)
        {
            mask.fillAmount = 0;
        }
    }

    public void Die()
    {
        Destroy(gameObject);
    }
 
}
public class Bullet : MonoBehaviour
{
    public float speed;
    public float damage;

    Rigidbody2D rb2d;
    // Start is called before the first frame update
    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
        rb2d.velocity = transform.up * speed;

        Destroy(gameObject, 3);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.gameObject.GetComponent<HealthSystem>() != null)
        {
            HealthSystem _healtSystem = collision.gameObject.GetComponent<HealthSystem>();
            _healtSystem.TakeDamage(damage);
        }
        Destroy(gameObject);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *