Liu Hao
Liu Hao

Reputation: 512

why do we need to Instantiate the loaded asset after LoadAsset in Unity AssetBundle?

In the manual of AssetBundle usage, https://docs.unity3d.com/Manual/AssetBundles-Native.html

I can see that when use LoadAsset loaded an GameObject, why we need to do the extra step Instantiate it ? this will create another copy of the prefab, I'm confuse why we do not use the loaded prefab GameObject directly?

public class LoadFromFileExample extends MonoBehaviour {
    function Start() {
        var myLoadedAssetBundle = AssetBundle.LoadFromFile(Path.Combine(Application.streamingAssetsPath, "myassetBundle"));
        if (myLoadedAssetBundle == null) {
            Debug.Log("Failed to load AssetBundle!");
            return;
        }
        var prefab = myLoadedAssetBundle.LoadAsset.<GameObject>("MyObject");
        Instantiate(prefab); // why do not use prefab directly ?
    }
}

Upvotes: 0

Views: 1173

Answers (1)

Programmer
Programmer

Reputation: 125315

Instating prefabs really has nothing to do with AssetBundle. It's also the-same when using the Resources.Load API. You need to understand what prefab is before you can answer this question.

Prefabs are just GameObjects and Components put together and made to be re-usable. It is used so that if you want the-same type of Object, you won't have to manually create them over and over again every-time. You just instantiate the already created and saved prefab. This is really important when you want to share resources between multiple scenes.

When you load a prefab, it is only stored in the memory waiting to be used or instantiated. It's not visible in the scene or Hierarchy tab. There is no reason the loading function should also instantiate the prefab because you may not need it right when it is loaded. Usually prefabs are loaded when game is loading and then appropriate prefabs are instantiated during run-time when needed.

Finally, instantiating a prefab, crates a copy of it and put's in the scene. Any operation should be done on the instantiated object the loaded prefab.

Upvotes: 1

Related Questions