I have a script that handles the destruction of game objects based on what they collide with. I am trying to count the number of objects destroyed when they collide with specific objects. However, this is not happening. Instead, the counter is getting to "1" and no longer counting. Can anyone explain why?

public class Destroy:MonoBehaviour{
    public GameObject asteroid_explosion;
    public GameObject ship_explosion;
    private int destroy_count = 0;

    void OnTriggerEnter(Collider other){
        if(other.tag == "Boundary"){

        if(other.tag == "Bolt"){
            destroy_count = destroy_count + 1;
            Instantiate(asteroid_explosion, transform.position, transform.rotation);

        if(other.tag == "Player"){
            destroy_count = destroy_count + 1;
            Instantiate(ship_explosion, other.transform.position, other.transform.rotation);

Your destroy_count variable is class level, and after collision you are destroying the gameObject have this script attached. So every object will reach at max at 1 and then destroy :)

  • \$\begingroup\$ So I need to change it from a private to a public variable? \$\endgroup\$ – Robert Dec 20 '15 at 12:18
  • \$\begingroup\$ No, you need to update public variable of another class or any static variable if you have any class having all global variables \$\endgroup\$ – Hamza Hasan Dec 20 '15 at 12:19
  • 1
    \$\begingroup\$ For example, you have a class named Globals and that class having all the global variables. Like, public static float DESTROY_COUNT = 0; then you can access it from any where by, Globals.DESTROY_COUNT. Hope you got my point \$\endgroup\$ – Hamza Hasan Dec 20 '15 at 12:24
  • \$\begingroup\$ Ah ok, I think I get it now. So if I were to declare the variable in the GameControlelr script, I would need to access it within the Destroy class in the Destroy script and increment it that way? \$\endgroup\$ – Robert Dec 20 '15 at 12:28
  • \$\begingroup\$ Exactly. You are right :) \$\endgroup\$ – Hamza Hasan Dec 20 '15 at 12:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.