porters

Loading Files with Assests Manager


Assests Manager

In order to help developers load multiple assets, Babylon.js (starting with version 1.14) introduced the AssetsManager class.

This class can be used to import meshes into a scene or load text and binary files.

Using AssetsManager

To use it, you just have to instantiate it with a current scene:

var assetsManager = new BABYLON.AssetsManager(scene);

Then you can add tasks to the manager:

var meshTask = assetsManager.addMeshTask("skull task", "", "scenes/", "skull.babylon");

Each task provides an onSuccess and an onError callback:

meshTask.onSuccess = function (task) {
    task.loadedMeshes[0].position = BABYLON.Vector3.Zero();
}

You can do the same thing but with text and binary files:

var textTask = assetsManager.addTextFileTask("text task", "msg.txt");
textTask.onSuccess = function(task) {
    console.log(task.text);
}

var binaryTask = assetsManager.addBinaryFileTask("binary task", "grass.jpg");
binaryTask.onSuccess = function (task) {
    // Do something with task.data
}

Images are also supported through imageTask:

var imageTask = assetsManager.addImageTask("image task", "img.jpg");
imageTask.onSuccess = function(task) {
    console.log(task.image.width);
}

Textures can also be loaded, through textureTask:

var textureTask = assetsManager.addTextureTask("image task", "img.jpg");
textureTask.onSuccess = function(task) {
    material.diffuseTexture = task.texture;
}

The manager itself provides three callbacks:

  • onFinish
  • onTaskSuccess
  • onTaskError
assetsManager.onFinish = function(tasks) {
    engine.runRenderLoop(function() {
        scene.render();
    });
};

Finally, to launch all the tasks, you have to call:

assetsManager.load();
  • You can see a live demo here
  • Playground demo here -

Using loading screen

By default, the AssetsManager will display a loading screen while loading assets:

If you want to disable the loading screen, you have to set useDefaultLoadingScreen to false:

assetsManager.useDefaultLoadingScreen = false;

The loading screen will also be displayed while loading a scene using SceneLoader if ShowLoadingScreen is set to true (by default).

BABYLON.SceneLoader.ShowLoadingScreen = false;

In the same way, you can also display or hide the loading screen manually using these functions:

engine.displayLoadingUI();
engine.hideLoadingUI();

Loading text is controlled using loadingUIText :

engine.loadingUIText = "text";

Background color is controlled using loadingUIBackgroundColor :

engine.loadingUIBackgroundColor = "red";