unity fall damage code example

Example: unity fall damage c#

using UnityEngine;

public class Collisions : MonoBehaviour
{
    [Tooltip("In Meters")]public float distanceAllowedToFall;

    float jumpHeight;
    float landingHeight;
    float fallDistance;

    private void OnCollisionExit(Collision collision)
    {
        jumpHeight = transform.position.y;
    }

    private void OnCollisionEnter(Collision collision)
    {
        landingHeight = transform.position.y;
        HealthDrain();
    }

    void HealthDrain()
    {
        fallDistance = jumpHeight - landingHeight;

        if (fallDistance > distanceAllowedToFall)
        {
            // Damage Player
        }
    }
}