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);
}
}
}
}