How to destroy a missile after it explodes?
Destroy(gameObject) will destroy the game object the script is attached to, if you’re using OnCollisionEnter() on the missile try this instead:
function OnCollisionEnter(col : Collision){
Destroy(col.gameObject);
}
That will destroy the object it hits instead. If you wanted an explosion etc to appear first it must be called before the Destroy otherwise it wount be read!
This is how you making a Missle Instantiate and find an object(s) with a certain tag!
It is in C#. You may have to change it to suit your needs better, but it does work!
Attach this script TO YOUR PREFAB THAT GETS INSTANTIATED!
Transform Target;
float Speed = 20f;
float MaxDistance = 50f;
float DieTime = 1.5f; // Destroyed in 1.5 seconds (Change to
// Change to your needs!)
void Start(){
DieTime = Time.time;
Target = GameObject.FindGameObjectWithTag ("Player").transform;
}
// Update is called once per frame
void Update ()
{
transform.LookAt (Target);
AI ();
if (Time.time - DieTime > 1.5f) {
Destroy (this.gameObject);
Debug.Log ("DESTROYED BY TIME");
Destroy (this.gameObject);
}
if(Target == null){
Target = GameObject.Find ("Player").transform;
}
}
void AI()
{
if (Vector3.Distance (transform.position, Target.position) <= MaxDistance) {
transform.position += transform.forward * Speed * Time.deltaTime;
}
}
void OnDestroy(){
if (Target) {
Destroy (gameObject);
Debug.Log ("Missile Destroyed");
}
}
}
As said, you may have to change things up for your needs, but this DOES WORK! in C#.
Hope this answered your question properly!
If so please mark as answered.