How to Destroy a prefab avoid to destroying assets is not permitted to avoid data loss problem
public GameObject[] newStreetArray;
public GameObject newStreet;
public GameObject currentStreet1;
private GameObject _oldStreet;
// Update is called once per frame
void OnTriggerEnter(Collider other)
{
if (other.tag == "Start")
{
if (_oldStreet != null)
{
Destroy(_oldStreet);//The problem is here.
}
else
{
Destroy(GameObject.Find("MainScene"));
}
}
else if (other.tag == "Middle")
{
SpawnLevel();
}
}
void SpawnLevel()
{
_oldStreet = currentStreet1;
newStreet = newStreetArray[Random.Range(0, newStreetArray.Length)];
currentStreet1 = (GameObject)Instantiate(newStreet, currentStreet1.transform.GetChild(2).position, Quaternion.identity);
}
The first prefab is level1 ,the player comes the middle , create a new prefab randomly and level 1 destroy, but i have an error (destroying assets is not permitted to avoid data loss). What is the problem.How can i fix this ?
Answer by dacarrera · Nov 14, 2019 at 01:16 AM
The error message is pretty on point with this. Destroy quite literally destroys it's parameter. Right now you're calling destroy directly on _oldStreet which will destroy the actual asset. This isn't "get rid of this from the scene please" it's actually "banish this from existence for the rest of eternity." So to workaround this, create a copy of what you want to destroy, then just use that and destroy it when you want.
For example, you can instantiate a prefab with Instantiate(whatToInstantiate)
. So you can do something like GameObject oldStreetCopy = Instantiate(_oldStreet);
and then use Destroy(oldStreetCopy)
instead, which will destroy a copy instead of the original from memory.
I can not implement your comment in my code :( How can i do that ?
Your answer
Follow this Question
Related Questions
How to load images in Loading Screen ? 0 Answers
how to move multi scenes in unity using android studio buttons 0 Answers
How get position from a prefab? 0 Answers
problem with prefab's script 1 Answer
Prefab Direction - shooting 2 Answers