destroing assets not aowed

hi friend

my problem is when i destroy an prefab in its script that attach to its gameobject there is

not an error but when i destroy a prefab in script that attach another gameobject there is

an error(“destroying an asset is not premitted to avoid data loss”)

it is my code

public class Projectile : MonoBehaviour {
public float speed;
public GameObject Enemy;
public GameObject Explosion;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update ()
{

gameObject.transform.Translate(Vector3.forward* Time.deltaTime * speed);

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
    
}

}

void OnTriggerEnter(Collider colide)
{
Destroy(gameObject);
Instantiate(Explosion, transform.position,Quaternion.identity);
}

That should fix your issue.

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.