unity-game-engineassetbundle

How to properly use prefabs from AsssetBundles?


I've recently encountered AssetBundles and tried to implement it in my project. I have a pretty simple game where controlling a character you should collect coins. I created the AssetBundle where I made prefabs and put everything from the game scene (background, player, terrain, etc...) into the AssetBundle. However, when loading objects from the bundle to the game scene, despite having the same size and transform parameters in the inspector, they are bigger than their original prefabs when starting a game. When it comes to the loaded character, not only is it ten times the size of the original but it also needs to be readjusted in script dependencies during the game to control it with a joystick. In terms of prefab size discrepancy, I think it has something to do with the loading screen as everything that comes out of the bundle is scaled to its size (see Fig.1) but I don't know why it happens nor how to fix it.

The script which loads prefabs:

public class LoadAssetBundles : MonoBehaviour
{

    AssetBundle loadedAssetBundle;
    public string path;
    public string assetName;

    void Start()
    {
        LoadAssetBundle(path);
        InstantiateObjectFromBundle(assetName);
    }

    void LoadAssetBundle(string bundleUrl)
    {
        loadedAssetBundle = AssetBundle.LoadFromFile(bundleUrl);

    }

    void InstantiateObjectFromBundle(string assetName)
    {
        var prefab = loadedAssetBundle.LoadAsset(assetName);
        Instantiate(prefab);
    }

}

Fig.1: The background loaded from the assetbundle, actual game scene is in the center of it

Fig.2: Inpector of original and bundle's version of the prefab Fig.3: Player prefab out of the bundle


Solution

  • Try setting your prefab root (the most outer gameObject) scale to 1, them rescale your sprites inside it.

    If you have a CanvasScaler on your canvas, the canvas scale will probably be lower than 1, something small like: 0.02321f, your object seems to have a high scale like 107.f or something, this may be the cause of the discrepancies. When instantiating, try passing a parent transform (where you want to place your prefab) and change the bool instantiateInWorldSpace (on/off) and see how it affects your prefab.

    public static Object Instantiate(Object original, Transform parent, bool instantiateInWorldSpace);
    

    Check docs: https://docs.unity3d.com/ScriptReference/Object.Instantiate.html