Trying to instantiatea prefab then destroy it and the gameobject it was spawned on
void OnTriggerEnter2D(Collider2D other) { if (other.tag == "Player") { Destroy(other.gameObject); gameObject.SetActive(false); GameObject clone = (GameObject) Instantiate(explosion, gameObject.transform.position, Quaternion.identity); Destroy(clone); Destroy(gameObject);
}
}
Here's my code. However neither gameobject is destroyed and it throws up an Error "Cannot cast from source type to destination type".
I think you should add a separate script to your explosion prefab that handles it's own destruction.
Answer by Makri907 · Nov 08, 2016 at 12:04 AM
GameObject explosion;
void Start(){
explosion = Resources.Load<GameObject>("Prefabs/explosion");
}
void OnTriggerEnter2D(Collider2D other){
if(other.tag=="Player"){
Destroy(other.gameObject);
Instantiate(explosion, transform.position, Quaternion.identity);
Destroy(explosion);
Destroy(gameObject);
}
}
}
Note: You will have to create a Resource folder, then a Prefabs sub-folder, then move your explosion prefab into the Prefab sub-folder. Add this script to the object you intended, and you will get the result you want.
Your answer
![](https://koobas.hobune.stream/wayback/20220612100247im_/https://answers.unity.com/themes/thub/images/avi.jpg)