Unloading a prefab using Resources.UnloadUnusedAssets.

When I try and unload a prefab loaded using the Resources.Load(), I get an error saying gameobjects cannot be unloaded using Resources.UnloadAsset(). So the other way to do it was destory the instances of the loaded prefab in the scene and then call Resources.UnloadUnusedAssets. But when I do this, the instances are destroyed but the prefab is not unloaded and hence even the texture it access stays in memory. Only when I call Destroy on the prefab itself and then call Resources.UnloadUnusedAssets do I see the prefab and texture unloaded from memory. But then I get an error stating “Destroying assets is not permitted to avoid data loss. If you really want to remove an asset use DestroyImmediate (theObject, true);”. Here is my code example:

private GameObject prefab;
private GameObject instance;

void loadGameobject() {
      prefab = Resources.Load("test/buildings", typeof(GameObject)) as GameObject;
      instance = (GameObject)Instantiate(prefab);
}

void unloadGameobject() {
      Destroy(instance);
      Destroy(prefab); // this line gives me error, destroying asset is not permitted
      Resources.UnloadUnusedAssets();
}

Let me know what I am doing wrong, and how do you successfully unload prefabs.

Found the problem, its not unloading because I have a reference to the prefab. Instead if I don’t maintain a reference things get unloaded when i delete the instance and call Resources.UnloadUnusedAssets(). Here is the modified code:

private GameObject instance;
 
 void loadGameobject() {
       instance = (GameObject)Instantiate(Resources.Load<GameObject>("test/buildings");
 }
 
 void unloadGameobject() {
       Destroy(instance);
       Resources.UnloadUnusedAssets();
 }

Hope this helps someone.