Hi I’m very new to unity working on my first project and I’ve been trying to code a basic enemy health system where if you hit an enemy a certain number of times he dies.
Now hit detection works fine, except even though in my scripts the enemy health is set to 10 and the player damage to 1, my enemy consistently dies in two hits instead of 10 and this won’t change no matter what I set the numbers to. Where did I mess up?
this is my enemy health script:
using UnityEngine;
public class EnemyHealth : MonoBehaviour
{
public float Health = 10;
private Animator _animator;
void Start()
{
_animator = GetComponent<Animator>();
}
public void TakeDamage(float damage)
{
if (Health <= 0)
{
return;
}
Health -= damage;
if (Health <= 0)
{
Death();
}
}
private void Death()
{
_animator.SetTrigger("dead");
}
}
and this is my player shooting script:
using UnityEngine;
public class PlayerShootingController : MonoBehaviour
{
// range for hit
public float Range = 100;
public Camera _camera;
public ParticleSystem _particle;
private LayerMask _shootableMask;
void Start()
{
_camera = Camera.main;
_particle = GetComponentInChildren<ParticleSystem> ();
//lock curser to middle of screen for shooting
Cursor.lockState = CursorLockMode.Locked;
//shootable layer assigned to enemies
_shootableMask = LayerMask.GetMask("Shootable");
}
void Update()
{
//if mouse is pressed
if (Input.GetMouseButton(0))
{
//create raycast from camera to mouse position
Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit();
//if raycasts hits something on shootable layer
if (Physics.Raycast(ray, out hit, Range, _shootableMask))
{
//print hit to console
print("hit " + hit.collider.gameObject);
//play particle system animation
_particle.Play();
//run enemy health script
EnemyHealth health = hit.collider.GetComponent <EnemyHealth> ();
//have enemy take 1 damage on hit
if (health != null)
{
health.TakeDamage(1);
}
}
}
}
}
can’t figure out where I went wrong, any help would be greatly appreciated