if (gameObject.transform.position.z > 23)
{
Destroy(gameObject);
}
}
void OnTriggerEnter(Collider colide)
{
Destroy(gameObject);
Instantiate(Explosion, new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, gameObject.transform.position.z),Quaternion.identity);
Destroy(Explosion); // this is where error showup
}
Before anyone comes to say “Put the Destroy(gameObject); at the end, that will fix it”, no need, Destroy is delayed to the end of the current frame so it is fine where it is.
Your main problem is that you try to destroy the prefab and not the instantiated object. The prefab is an asset, if you would destroy it, it would be gone forever.
void OnTriggerEnter(Collider colide)
{
Destroy(gameObject);
GameObject clone = (GameObject)Instantiate(Explosion, gameObject.transform.position, Quaternion.identity);
Destroy(clone, 3); // destroy after 3 sec.
}
Usually it’s better to control the destruction of such temporal effects on the effect itself like @fafase said. When you use the legacy particle system the ParticleAnimator has an “Autodestruct” option which will destroy the gameobject when the particle effect is done. This of course only works with one shot particle effects.
An alternative is to attach another script to the Explosion prefab which handles the destruction of itself.