So I have a script spawning enemies in my scene. Every enemy game object has an enemy script on it that detects a tap or mouse click.
When a click on enemy is detected the health decrements and if it goes below 0 that gameObject is destroyed.
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (hit.transform.tag == "Enemy")
{
health--;
if (health <= 0)
Destroy(gameObject);
}
}
}
}
The problem is that when I click on an enemy, every enemy in the scene takes damage rather than just the one I am clicking on.
Can't figure out why this is. As for some reason the raycast
applies to all the enemies in the scene rather than where I am clicking?
Any ideas?
Thanks