Search code examples
c#unity-game-engineassetbundle

Destroying loaded assets from a Unity Asset Bundle


I've got an asset bundle loading in my project and I'm adding all of them to a list so that I can iterate through each of the individual object inside the asset bundle. However, I'm having trouble deleting the loaded object when I no longer need it in my scene.

In my research I know of the Bundle.UnloadAll but from what I've read it destroys the entire bundle which I don't want. Right now my code looks like this:

if(GUI.Button(new Rect(10,130,100,50), "Forward"))
{
    if( index > 0 && object_List[index] != null)
    {
        Destroy((GameObject)object_List[index]);
    }

    Instantiate((GameObject)object_List[index]);
    index ++;
}

This code iterates through my list containing the loaded in asset bundle objects and should spawn the next one in the list. At the same time, it should destroy the previously loaded one. But when I run this code, I get the following error:

Destroying assets is not permitted to avoid data loss. If you really want to remove an asset use DestroyImmediate (theObject, true);

So I change my code to its suggestion and I run into this error:

MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.

However, nothing gets removed from my list and the first object to get spawned still remains.

Has anyone ever ran into a similar problem? Is what I'm trying to do even possible?

Any help would be appreciated.


Solution

  • The mistake you're making, is that you're trying to destroy the asset, not the ingame gameObject. When you call Instantiate((GameObject)object_List[index]); it returns a reference to the loaded object, so for example :

    GameObject myObject = Instantiate((GameObject)object_List[index]);

    will give you the object, and later you'll want to call Destroy(myObject); to destroy it.

    Instead of destroying them, you could perhaps try disabling / enabling the gameobjects when needed (though it's not clear why you're destroying them, so this might not serve your purposes).

    if(GUI.Button(new Rect(10,130,100,50), "Forward"))
    {
        if( index > 0 && object_List[index] != null)
        {
            ((GameObject)object_List[index]).SetActive(false);
        }
    
        ((GameObject)object_List[index]).SetActive(true);
        index ++;
    }