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.