Deal damage to an object while using Raycast

So I’ve created an object and I’ve added a health bar, but when I want to shoot while using RayCast it stops the game. I don’t know what can I do more or change. I don’t want to create projectiles/balls to shoot.

So this is EnemyHealth assigned to Enemy object:
using UnityEngine;

public class EnemyHealth : MonoBehaviour
{
    public float maxHealth = 100f;
    public float health;

    void Start()
    {
        health = maxHealth;
    }
    
    public void TakeDamage(float damageAmount)
    {

        health -= damageAmount;
        if(health <= 0)
        {
            Destroy(gameObject);
        }
    }
}

And this is code where I shoot:
using UnityEngine;

public class HitEnemy : MonoBehaviour
{
    [SerializeField] Camera cam;
    void Update()
    {
      

        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = cam.ViewportPointToRay(new Vector3(0.5f, 0.5f));
            if (Physics.Raycast(ray, out RaycastHit hit))
            {
                gameObject.GetComponent<EnemyHealth>().TakeDamage(10);
            }


        }
    }     
}

Use

if (Physics.Raycast(ray, out RaycastHit hit))
{
    hit.collider.gameObject.GetComponent<EnemyHealth>()?.TakeDamage(10);
}

to deal damage to the actual object that’s been hit by the ray. This way you can attach the script to any appropriate game object (like, in your case, e.g. the camera).

As @ojaoweir already mentioned, with your version, the EnemyHit script needs to be attached to every enemy to work and damage is dealt if the ray hits any collider, not only when hitting an enemy. And with multiple enemies on screen, this way would lead to chaos and madness :wink:

The question mark after GetComponent() makes sure, that TakeDamage(10) is called only if the gameObject that’s been hit has an EnemyHealth script attached.