Health and Damage Scripts. (Not Looking for one)

I recently got a Health and Damage script, and I love sharing things with others, such as scripts that help begginers.
Health

using UnityEngine;
using UnityEngine.UI;

public class Health: MonoBehaviour
{
    #region Properties

    [SerializeField] private int healthInitial = 3;

    private int healthCurrent;
    public Text m_text;

    #endregion

    #region Initialisation methods

    void Start()
    {
        ResetHealth();
    }

    public void ResetHealth()
    {
        healthCurrent = healthInitial;
        m_text.text = healthCurrent.ToString();
    }
 
    void Update()
    {
                m_text.text = healthCurrent.ToString();
    }
    #endregion

    #region Gameplay methods

    public void TakeDamage(int damageAmount)
    {
        healthCurrent -= damageAmount;

        if (healthCurrent <= 0)
        {
            Destroy(gameObject);
        }
    }

    public void Heal(int healAmount)
    {
        healthCurrent += healAmount;

        if (healthCurrent > healthInitial)
        {

        }
    }

    #endregion
}

Damage

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

public class Damage : MonoBehaviour {

    public int damageAmount = 10;

    void OnTriggerEnter(Collider coll)
    {

            coll.gameObject.GetComponent<Health>().TakeDamage(damageAmount);
        }

    }

You can duplicate the Damage script to make a Heal Script, but I didn’t add one.

As written, your Damage script will null reference error whenever an object enters the trigger which lacks a Player component. I’d suggest just checking for it first before trying to use it.

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

public class Damage : MonoBehaviour {

    public int damageAmount = 10;

    void OnTriggerEnter(Collider coll)
    {
        Player playerComponent = coll.gameObject.GetComponent<Player>();
        if (playerComponent != null)
        {
            playerComponent.TakeDamage(damageAmount);
        }
    }
}
1 Like

Oh, I didn’t notice that, I have tried to use it, and it works.