- Home /
Why does killing one enemy kill them all?
I saw a lot of similar questions but non of them helped me, and they were old too. So I want to ask that in the script below when kill an enemy, automatically the currentHelath of all enemies go down. Can someone tell me what is wrong with the script?
Note: currentHealth is a non-static variable defined in characterStats class. and I call the fire method in PlayerGun script.
void Fire()
{
muzzleFlash.Play();
gunSound.Play();
currAmmo--;
animator.SetInteger("condition", 6);
RaycastHit hit;
if (Physics.Raycast(transform.position, Camera.main.transform.forward, out hit, database.weapons[id].range))
{
nextTimeToFire = Time.time + 1f/database.weapons[id].fireRate;
if (hit.transform.tag == "Enemy")
{
CharacterStats enemyStat = hit.transform.GetComponent<CharacterStats>();
if (!enemyStat.isDead)
{
enemyStat.TakeDamage(database.weapons[id].damage);
if (enemyStat.currentHelath <= 0)
{
enemyStat.isDead = true;
coins = coins + 10;
coinsText.text = coins.ToString();
enemyAnim.SetTrigger("isDeadTrigger");
}
}
}
if (hit.rigidbody != null)
{
hit.rigidbody.AddForce(-hit.normal * impactForce);
}
GameObject impactGO = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(impactGO, 1f);
}
}
How do you get
enemyAnim
?Why isn't it the CharacterStats which handles the dead of the character and its animation?
Answer by CmdrZin · Dec 11, 2020 at 04:57 PM
Try
if( hit.transform.position == transform.position )
or the collider to determine it the ray hit this object. Then check for Enemy tag. Another way to detect a hit is with OnMouseDown() in your target's script.
see https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html
Thank you for the answer, but none of the above works! I don't use any Triggers for this. currently I have two prefabs of enemy in my scene. and when I kill one, the second one dies and falls down. but the one that got the shot, does not fall down, only the health reduces. I think the problem is in CharacterStats enemyStat = hit.transform.GetComponent<CharacterStats>();
since it loads the health script for the enemy. so I think it loads for all and affects for all as well. but I can't figure it out.
Well, the only other thing would be variables that are static. This would make them common to all prefabs instead of independent for each. Good luck.
Have fun.
Your answer
![](https://koobas.hobune.stream/wayback/20220613021502im_/https://answers.unity.com/themes/thub/images/avi.jpg)