Console Error : " Destroying Assets is not Permitted to Avoid Data Loss "
I’m trying to destroy the effects I instantiated but it’s giving me this error. How else could I do this? I don’t want my effects to stay in the scene.
using UnityEngine;
using System.Collections;
public class HealthDamage : MonoBehaviour
{
public int maxHealth = 100;
public int currentHealth = 100;
public GameObject projectileExplode;
public GameObject enemyExplode;
void Update()
{
if (currentHealth < 1)
{
Destroy(gameObject);
Instantiate(enemyExplode, transform.position, transform.rotation * Random.rotation);
Destroy(enemyExplode, 2);
}
}
void OnCollisionEnter(Collision col)
{
if (col.gameObject.tag == "Projectile")
{
currentHealth -= 25;
Destroy(col.gameObject);
Instantiate(projectileExplode, transform.position, transform.rotation * Random.rotation);
Destroy(projectileExplode, 2);
}
}
}
enemyExplode and projectileExplode are just prefabs, the specifications which are copied to create in-game instances. When you call Instantiate(), you’re copying them, and getting a new object back. This copy is the one that you want to call Destroy(obj, delay) on, not the original prefab itself. For example:
var explodeInstance = Instantiate(enemyExplode, transform.position, transform.rotation * Random.rotation);
Destroy(explodeInstance, 2);
Also, in your Update() call, I’d recommend moving the Destroy(gameObject) to the line below Instantiate(), because you are using values belonging to the current game object (enemyExplode, transform) when calling Instantiate, and it is misleading to be using these values after already indicating that the object should be destroyed. It might function fine in Unity because Destroy() doesn’t take place immediately, but it still looks awkward to my general programming eyes.
You’re not calling destroy on the effect you instantiated. You’re calling destroy on the prefab/resource you instantiated it from. You’re never storing the reference to the instantiated object returned by the instantiate call.
What you are doing is essentially ordering a toy from the toy factory followed by burning down the toy factory. Like the others mentions you want to destroy the instance not the source.