how to destroy an instantiated object after the object it was referencing was destroyed.

I want to destroy a missile from a rocket launcher after the object it was targeting got destroyed from another tower.

missile control script

using UnityEngine;
using System.Collections;

public class MissileControl : MonoBehaviour {
public GameObject target;
public float speed = 2f;
public ParticleSystem explosionEffect;
EnemyHealthManager enemyHealth;
MissileLauncherTargettingSystem missileGameObject;

void Start() {
	enemyHealth = target.GetComponent<EnemyHealthManager> ();
}

// Update is called once per frame
void Update () {
	
	if (target != null) {
		
	
		
	transform.LookAt (target.transform.position);


	transform.position = Vector3.MoveTowards (transform.position, target.transform.position, Time.deltaTime * speed);

		if (Vector3.Distance (target.transform.position, transform.position) < 0.1f) {
			Instantiate (explosionEffect, transform.position, Quaternion.identity);
			enemyHealth.ReduceHealth (30f);
			Destroy (gameObject);

		}
	}

}

}

rocket launcher script

using UnityEngine;
using System.Collections;

public class MissileLauncherTargettingSystem : TurretTargettingSystem {
float lastFired;
public float fireDelay = 4f;
public GameObject missileGameObject;

override public void Start() {
	lastFired = Time.time;
	base.Start ();
}

override public void MaybeFire() {
	if (Time.time > lastFired + fireDelay) {
		// Instantiate Missile
		Vector3 instantionPosition = transform.position + (transform.forward * 0.4f);
		GameObject missile = Instantiate(missileGameObject, instantionPosition, Quaternion.identity) as GameObject;
		MissileControl missileControl = missile.GetComponent<MissileControl> ();
		missileControl.target = currentTarget;
		lastFired = Time.time;
	}
}

override public void EngagedTarget() {
}

override public void DisengagedTarget() {
}

}

check if the target == null, destroy itself ?

What Le_Valius is saying should work perfectly…

You check:

 if (target != null)

~do missile stuff~

just add :

else{
    Destroy(gameOject);
}

between lines 24 and 25 of the missile script.

You said that it gets destroyed before anything happens, well that means your target variable is null, and should be destroyed. You don’t show any code of where you assign the initial value to your target variable.

Just make sure that you assign a value to target in code above/before the code that checks to see if it has a target.

You also have a currentTarget which get’s assigned to target you might need to check

else if(currentTarget == null){
    Destroy(gameObject);
}

I am not 100% though, as we don’t have all the code.

It’s a really simple fix you’ll get it. = )