Object Damageable

Open World - Scripts - Object Damageable

How to make a Damagabled Object in Unity3D with C#

To make a Damagabled object simply add the following script and on the object in unity make sure the Game Object has a collider so that on Collision or Raycast hit you can simply call GetComponent().TakeDamage(value) with value being the ammount of damage to take.

if (OnZeroHealth == null)

ObjectDamageable.cs 844B


using UnityEngine;
using UnityEngine.Events;

[RequireComponent(typeof(MeshCollider))]
public class ObjectDamageable : MonoBehaviour
{
    public UnityEvent OnZeroHealth;
    [SerializeField] float ObjectDamage = 100;
    [SerializeField] bool DestroyOnZeroHealth = true;

    void Start()
    {
        if (DestroyOnZeroHealth)
        {
            if (OnZeroHealth == null)
            {
                OnZeroHealth = new UnityEvent();
            }
            OnZeroHealth.AddListener(DestroyMe);
        }
    }
    void DestroyMe() => Destroy(gameObject);

    public void TakeDamage(float damage)
    {
        ObjectDamage -= damage;
        if (ObjectDamage <= 0)
        {
            if (OnZeroHealth != null)
            {
                OnZeroHealth.Invoke();
            }
        }
    }
}
Powered by w3.css