Hello I’m having a hard time destroying my object after multiple collisions. My enemy destroys after the first hit & I would want it to destroy after multiple hits I need help.
public int hitsneeded;
int hits;
void OnTriggerEnter2D (Collider2D col)
{
if (col.gameObject.tag == “Bullet”)
{
hits++;
if (hits >= hitsneeded)
{
Destroy(gameObject);
}
}
}
public int health = 10;
private int hits;
void Update () {
if (health <= 0)
{
Destroy(gameObject);
}
}
public void DeductPoints (int damageAmount) {
health -= damageAmount;
}
void OnTriggerEnter2D (Collider2D col)
{
if (col.gameObject.tag == “Bullet”)
{
DeductPoints(5); //Will destroy in two shots.
}
}
I am going to take a fun guess and say you are shooting more than one bullet without you knowing it (or something equivalent to that). The code should work with a basic setup of a single gameObject hitting it.
You could also have mutliple colliders (child gameObjects) on your bullet that are tagged “Bullet”. This could also grant multiple hits.
You need to debug how many bullets are firing, whats on the bullet that could be an extra tag, is there other objects that you accidentally tagged as “Bullet” that is hitting the character. Does the character itself have a collider with a tag as “Bullet”
The detection looks fine. But it looks like you don’t remove the bullet. Try destroying the col.gameObject before doing the hits++;
I would handle the bullet spawns like this.
This way you’re sure you are only spawning one bullet each X seconds and it will work for all weapons imaginable.
float fireRate = 1f; // How fast can we fire?
float lastShot; // When did we shoot last?
void Update ()
{
if ( Input.GetMouseButtonDown)(0) ) // LMB is down
{
if ( Time.time - lastShot > fireRate ) // Is the last shot longer ago than the fireRate?
{
Fire(); // Shoot!
lastShot = Time.time; // Register the time of the last shot
}
}
}
void Fire(){
// Didn't change anything here
Vector3 offset = transform.rotation * new Vector3 (0, 0.5f, 0);
Instantiate (Bullet, transform.position + offset, transform.rotation);
AudioSource.PlayClipAtPoint(sound, transform.position);
}