Hi,
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.
Any ideas?
Thanks
if (hit.transform.tag == "Enemy")
{
health--;
if (health <= 0)
Destroy(gameObject);
Is this bit reducing the health of everything with the Enemy tag globally? It doesn’t seem like it’s singling out the hit.transform it is hitting?
Health seems to be declared on the player, so naturally that will effect all enemies. It should be declared on the enemy and decreased when you hit it
1 Like
@farazk86 what is happening in your script is, when ray hits any object, every object checks for same ray. In your case, doesn’t matter which object is being hit, as long at least one is hit. Further each object reduces its health.
OnUpdate aimply go through every script attached to game objects.
What you would need, to check if hit collider, transform, or game object (hash), is the same, as as the object, to which script is attached to.
Problem is, you run ray collision check on every game object per frame. You should really run one ray check in frame and compare hit results.
Simply, create single script, check ray collision, use for loop to iterate through all related objects, and check if hit object is same as the any of looped object. If so, reduce object’s health.
In such case, you need access health reference of the hit object.
1 Like