Deleting prefab located in Project in scripts

Hi, I am trying to edit a prefab located in the Project (on the hard drive) and doing some delete operations (such as Destroy a Component). But when I try to do that with DestroyImmediate, I got a “Destroying assets is not permitted to avoid data loss” error and I fail to modify the prefab.

Is there any work around with this without using DestroyImmediate()? I was thinking to create a instance of the prefab and then apply the change back to the prefab, but this does not work for cases where the GameObject is a child of the prefab.

Thanks.

Here is a sample code of what I am doing DestroyImmediate(Prefab.GetComponent()); where Prefab is the GameObject prefab.

OK, so to make sure I’m understanding you correctly, you’re trying to destroy prefab objects from within the Editor, not during Runtime, correct? If that is in fact what you are wanting to do, permanently destroy something in one of your folders, then you’d want to set it up more like

DestroyImmediate(Prefab, true);

Just keep in mind what DestroyImmediate is for… I’d hate to see you losing valuable data accidentally…

“Destroys the object obj immediately. You are strongly recommended to use Destroy instead.”
“This function should only be used when writing editor code since the delayed destruction will never be invoked in edit mode. In game code you should use Object.Destroy instead. Destroy is always delayed (but executed within the same frame). Use this function with care since it can destroy assets permanently! Also note that you should never iterate through arrays and destroy the elements you are iterating over. This will cause serious problems (as a general programming practice, not just in Unity).”

2 Likes

Thank you so much for the help krougeau. You just made my day : ) I did not realize that there is an optional parameter for DestroyImmediate.
Yes I understand what I am doing, I am making a nested prefab system I use this function for updating the connected prefab. (Also there is git for backup too : D)

2 Likes

Cool beans :slight_smile: So glad it helped!

Hello, I would like to know is there a way to delete prefab during game mode ? For eg. what I am trying to achieve is that when in one level player reaches finish line and clicks on next level the lock sprite/gameobject from the level screen disappears/destroyed. I have added the lock gameobject/sprite as a prefab and trying to destroy it using code. It runs fine in editor but not when I build the game. Thanks

Would like to know that too. I have a level select menu with buttons added to the resource folder as prefabs. When i hit delete i want to delete not only the button in the scene