I want to destroy this gameobject when this gameobject is destroyed.

I’m a beginner in unity. I just want to ask about destroying a certain game object.

We have an assignment that if we destroy the three game object, the last game object will destroy.

Example: a door have a three targets. if you destroyed the three targets, the door will open.

These are my codes.

using UnityEngine;
using System.Collections;

public class Fire1 : MonoBehaviour {
	//int ctr;
	GameObject player;
	// Use this for initialization
	void Start () {
		//ctr = 0;
		player = GameObject.Find ("Player");
		rigidbody.AddForce (player.transform.forward * 5000);
	}
	
	// Update is called once per frame
	void Update () {
	}

	void OnCollisionEnter (Collision col){
		if (col.collider.name == "Wall") {
			Destroy(gameObject);
		}
		if (col.collider.name == "Target"){
			col.collider.GetComponent<targetCounter>().setCtr();
			Destroy(gameObject);
		}
		if (col.collider.GetComponent<targetCounter> ().getCtr () >= 3) {
			col.collider.GetComponent<destroyCounter>().setCtr();
			Destroy (col.gameObject);
		}
		if (col.collider.GetComponent<destroyCounter>().getCtr()>=3) {
			Destroy (GameObject.FindWithTag("Door"));
		}
	}
}


using UnityEngine;
using System.Collections;

public class targetCounter : MonoBehaviour {

	int ctr;
	public Material green;
	public Material blue;

	// Use this for initialization
	void Start () {
		ctr = 0;
	}
	
	// Update is called once per frame
	void Update () {
	}
	
	public void setCtr(){
		ctr++;
		if (ctr == 1) {
			GetComponent<MeshRenderer>().material = green;
		}
		if (ctr == 2) {
			GetComponent<MeshRenderer>().material = blue;
		}
	}
	
	public int getCtr(){
		return ctr;
	}
}

using UnityEngine;
using System.Collections;

public class destroyCounter : MonoBehaviour {
	int ctr;
	// Use this for initialization
	void Start () {
		ctr = 0;
	}
	
	// Update is called once per frame
	void Update () {
		Debug.Log (ctr);
	}

	public void setCtr(){
		ctr++;
	}
	
	public int getCtr(){
		return ctr;
	}
}

MonoBehaviour.OnDestroy

This function is called when the MonoBehaviour will be destroyed.

OnDestroy will only be called on game objects that have previously been active.

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void OnDestroy() {
        print("Script was destroyed");
    }
}

I suppose inside that destroy function you could add something like:

FindObjectOfType(typeof(destroyCounter)).ctr++;

Expose your ctr variable as a public so you can access it from other scripts.