- Home /
Destory a single prefab when hit with Raycast
Hello, I am having an issue with Destroying a single prefab by lowering a single prefabs int to 0 without doing so to all other prefabs.
So the player "shoots" at a enemy that has a certain amount of "health", once it hits 0 the gameObject is destroyed. But my script takes the amount of "Damage" from all prefabs and not just the one that is being hit.
Here is the shooting script
void FixedUpdate() {
if (shooting) {
shooting = false;
flash.GetComponent<ParticleSystem>().Play();
RaycastHit hit;
Debug.DrawRay(transform.position, -transform.right, Color.green, 50f);
if(Physics.Raycast(transform.position, -transform.right, out hit, 50f)) {
if(hit.transform.tag == "Enemy") {
Instantiate(impact, hit.point, transform.rotation);
enemyAttack.enemyHp -= 5;
if(enemyAttack.enemyHp < 0) {
Destroy(hit.collider.gameObject);
}
}
}
}
}
The enemies Health is being controlled by a script that is on the prefabs. It is just
public static int enemyHp = 200;
This at some degree does work, if the player shoots at an enemy enough then it will be destroyed but all other prefabs enemyHp is at 0. So what is taken from on prefab is taken from the others. and then each prefab is destroyed with a single hit after that.
Thank you for any help guys
Answer by pako · Sep 02, 2015 at 01:07 PM
You have made the enemyHp a static field. This means that enemyHp is not part of each instance of the enemy prefab, but it applies to all instances of the enemy prefab. So, remove the static keyword, and then each enemy will have its own enemyHp:
public int enemyHp = 200;
This way, only the enemy instance that is being hit by the player will have its health reduced.
I will give that ago, I am not even sure why it is static, not sure why I made it Static. Thanks for pointing it out!
Your answer
Follow this Question
Related Questions
How to effect and apply a common material to children individually... 2 Answers
Multiple Cars not working 1 Answer
Grid Placement In Game 2 Answers
How to spawn prefab only in allowed area? 0 Answers
Spawned tree not falling 1 Answer