- Home /
 
Could someone show me examples of how to use void OnDestroy() to instantiate an object?
Okay I have been doing some research along with going through the Unity manual and checking existing answers and I still havent fully understood what its doing or how you can use OnDestroy to instantiate a gameobject after destroying a gameobject(an enemy) Here is my script
 public GameObject itemToDrop;
 
 private void OnDestroy(other)
     {
         Instantiate(itemToDrop, other.transform.position, other.transform.rotation);
     }
 
 
 
 **Heres unitys example but I'm not sure how it can be used to instantiate a gameobject** 
 public class ExampleClass : MonoBehaviour {
     void OnDestroy() {
         print("Script was destroyed");
     }
 }
 OnDestroy cannot be a co-routine.
 
              Answer by allenallenallen · Mar 28, 2017 at 05:02 PM
So your OnDestroy is actually not the one Unity provides because you have a parameter.
 GameObject itemToDrop;
 void OnDestroy(){
     Instantiate(itemToDrop, transform.position, transform.rotation); // Assuming you are dropping the object exactly where the enemy died
 }
 
              Answer by shadowpuppet · Mar 28, 2017 at 07:43 PM
why not include the item drop with the destroy? My example below instantiates a ragdoll but could just as easily instantiate item ToDrop. This script destroys enemy and leaves ragdoll prefab in it's place when shot ( hitbyray) or if a grenade explodes near him.
 using UnityEngine;
 using System.Collections;
 
 public class destroyandDrop : MonoBehaviour {
 
     public GameObject enemy;
     public GameObject prefab;
 
     void HitByRay () {
         Debug.Log ("yippee! you shot me");
         Destroy (enemy);
         Instantiate(prefab, transform.position , transform.rotation);
         
     }
     void OnTriggerEnter (Collider other) {
 
         if(other.tag == "Grenade")
             Destroy(enemy);
         
         if(other.tag == "Grenade")
             Instantiate(prefab, transform.position , transform.rotation);
     
             
     }
 }
 
              Your answer
 
             Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Store Game Object Into List For Later Reinstantiation? 0 Answers
Destroy doesn't work when also instantiating new objects 1 Answer
Destroy the current GameObject? 7 Answers
"Destroy assets is not permitted to avoid data loss" 2 Answers