Destroying assets is not permitted to avoid data loss
Destroying assets is not permitted to avoid data loss.
Destroy was called on an asset in your project, almost always the prefab itself, instead of the copy Instantiate made. Unity refuses, because destroying the asset would delete it from your project.
Read the Console line first
The stack trace names the Destroy call. Check whether the variable you pass holds the prefab or the instance.
Common causes
Destroying the prefab instead of the instance
Instantiate returns the new copy. If you ignore that return value and later Destroy the prefab field, you are destroying the template.
ExampleC#Instantiate(explosionPrefab, transform.position, Quaternion.identity); Destroy(explosionPrefab, 2f); // destroys the asset, not the copyA prefab asset was dragged into a scene-object slot
A field meant to point at an object in the scene points at the prefab in the Project window instead. Drag the instance from the Hierarchy.
The fix
GameObject explosion = Instantiate(explosionPrefab, transform.position, Quaternion.identity);
Destroy(explosion, 2f);Stop it coming back
Always keep what Instantiate returns, and name prefab fields with Prefab at the end so a Destroy on one stands out in review. Pooling avoids destroying effects at all.
Questions
- Can DestroyImmediate get around this?
DestroyImmediate(asset, true)does delete the asset, permanently, from your project. That is almost never what you want at runtime. Destroy the instance that Instantiate returned instead.- Does the same apply to materials?
- Yes.
renderer.sharedMaterialis the material asset; destroying it is blocked.renderer.materialcreates a copy for that renderer, and that copy is the one to destroy when you are done with it. - How do I spot prefab fields at a glance?
- Name them with Prefab at the end, such as
bulletPrefab, and keep the instance in a separate variable. A Destroy on a field ending in Prefab then stands out in review.
Scripts that avoid it
Related errors
Got a different error? Paste it into the error lookup.