0

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

StuckInPhDNoMore
  • 2,507
  • 4
  • 41
  • 73

1 Answers1

3

Because you never check which enemy

This line: if (hit.transform.tag == "Enemy") only checks to see if the ray hit an enemy ("oh my god, they shot Bob!"). To check to see if the ray hit itself you want if(hit.transform == this.transform) instead ("I've been shot!").

Or better yet, don't have this code attached to all your enemies (10000 enemies, 10000 raycasts!) and have one script attached to something like the camera that performs the existing check, but replaces health--; line with hit.transform.GetComponent<Enemy>().Damage() which will deal damage only to the enemy the mouse is pointing at.

Community
  • 1
  • 1
  • 1
    Thank you. You're right putting this on camera also solved my problem and also solved the performance issues I was having as enemies in scene increased. :) – StuckInPhDNoMore Nov 24 '19 at 21:38