- Home /
Removing game object from scene in editor script
I have an editor script that's purpose is to create and save a prefab asset. I don't want to actually add this prefab to the scene (saving it to the assets is enough).
However, PrefabUtility.CreatePrefab has the side effect of instantiating the object in the scene.
I don't see a way to prevent CreatePrefab from doing this, so how can i remove the GO it instantiated from the scene?
Answer by Lysander · Dec 31, 2017 at 05:08 AM
Have you just tried using DestroyImmediate on the returned GameObject, but disallow destroying assets? I've never used PrefabUtility.CreatePrefab, so I had no idea it instantiated a copy immediately in the scene, but Unity has a tendency to return instantiated objects immediately, so there's a slight chance the returned object may be the instance rather than the prefab itself.
If that's not the case, I don't think Unity keeps track of 'last instantiated object' anywhere, so the only thing I can really think of is to iterate over every single GameObject in the scene (just use FindObjectsOfType(typeof(GameObject))) and use PrefabUtility.GetPrefabParent() and reference-check that against the prefab you just made (and should still have the reference to).
DestroyImmediate(foo, false) didn't do the trick...
"Destroying assets is not permitted to avoid data loss.
If you really want to remove an asset use DestroyImmediate (theObject, true);"
I'll try iterating through the scene and checking prefab references. Will report back if that works, sounds promising. Just wish there was a simpler way!!
Thanks!