How to destroy gameobject with 3 shoots?

Hi guys,

I want to make asteroid get destroyed when it’s hit 3 times, currently it’s being destroyed after one shot only, I use the code below. How could i implement it? Thank you so much in advance!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class DestroyByContact : MonoBehaviour
{
    public GameObject explosion;
    public GameObject playerExplosion;
    public int scoreValue;
    private GameController gameController;
 
    void Start ()
    {
        GameObject gameControllerObject = GameObject.FindGameObjectWithTag ("GameController");
        if (gameControllerObject != null)
        {
            gameController = gameControllerObject.GetComponent <GameController>();
        }
        if (gameController == null)
        {
            Debug.Log ("Cannot find 'GameController' script");
        }
    }
 
 
    void OnTriggerEnter(Collider other) {
        if (other.tag =="Boundary")
        {
 
        return;
    }
     if (other.tag == "Asteroid")
        {
            return;
        }
        Instantiate(explosion, transform.position, transform.rotation);
        if (other.tag == "Player")
        {
            Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
        }
    gameController.AddScore (scoreValue);
    Destroy(other.gameObject);
    Destroy(gameObject);
    }
}

Essentially, instead of directly executing the asteroid destruction code when it gets hit, you just count up a variable for how often it was hit (or down how many hits remain till destruction), and check for the required amount of hits, then execute the asteroid destruction code if that condition is true.


###Try the following steps:

  1. Try to separate the logic for destroying the asteroid from the logic for destroying the other object, and make sure the asteroid destruction code is encapsulated in one block of code, or even a separate method.
  2. Add a private member variable for the remaining health of the asteroid and initialize its value with the number of hits your asteroid shall take to destroy.
  3. Surround the code block (or method call) that deals with asteroid destruction with an if-clause checking if the remaining health is more than zero.
  4. Before the if-check, decrement the remaining health.

###Further remarks:

  • For comparing tags, there’s a dedicated method (see documentation) that is more efficient than doing a regular string comparison for tags.
  • Assuming this component script “DestroyByContact” is placed on your asteroids, there might be better places to store the information what explosion effects to spawn for certain other objects when they are hit.