I have a zombie set up in my game and a AK that fires set on player control. I have a enemy tag on my zombie and a health script. I also have trigger set on my zombie collision. I want my zombie health to decrease when the bullet hits the enemy and when it reaches 0 to play my prefab particle effect and destroy the enemy. I have tried a couple different thing but none seem to work.This Give me no errors but my enemy health does not decrease.
void OnTriggerEnter(Collider otherObject)
{
If this script is attached to the bullet (as it should be in this case), the problem is the wrong GetComponent reference - it must be otherObject instead of gameObject (gameObject references the bullet, not the enemy):
But even doing this some shots may be lost due to the bullet speed: fast projectiles may not be detected by the collision system (the bullet is before the target in one frame, and after it in the next).
If you experience this problem, change to “raycast shot”: cast a ray from the weapon and check the collider hit (if any); if it’s an enemy collider, reduce the enemy health - something like this (weapon script):
AudioClip shotSound; // drag the shot sound here
void Update(){
if (Input.GetButtonDown("Fire1")){
AudioSource.PlayClipAtPoint(shotSound, transform.position);
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit)){
if (hit.transform.tag == "enemy"){
enemyhealth eh = hit.transform.GetComponent();
eh.AddjustCurrentlength(-10);
}
}
}
}
The “raycast shot” is the preferred way to shot fast projectiles; instantiated projectiles are used only for slow weapons, like rocket launchers.