Loading multiple .stls and assigning different materials to each

Hello again,

Probably a common question but I can’t find a clear answer and whilst I have implemented something that sort of works I don’t know if it is best practice.

Essentially I have x3 .stl meshes which I would like to import and to each one assign a different material. I have imported the three meshes using an Asset Manager and this works but (a) I am not sure if this is the best way to import the meshes and (b) I don’t know the best way of assigning different materials to the x3 imported meshes contained within the manager.

Asset container code is as follows:

//Create an Asset Manager
var assetsManager = new BABYLON.AssetsManager(scene);

//Add Meshes
var meshTask1 = assetsManager.addMeshTask("", “”, “”, “isosurfaces_CpT0pt0Trimmed.stl”);
var meshTask2 = assetsManager.addMeshTask("", “”, “”, “isosurfaces_CpT0pt4Trimmed.stl”);
var meshTask3 = assetsManager.addMeshTask("", “”, “”, “isosurfaces_CpT0pt8Trimmed.stl”);

In order to assign materials I have done this in a callback (again probably not the best way of doing it) and whilst this works I dont really understand why. I would have thought that the [0] portion of the asset manager should increment as if each mesh in the container was contained like an array but when I try this no material gets assigned. The code below for some reason works.

//Assign Materials
meshTask1.onSuccess = function (task) {
task.loadedMeshes[0].material = myMaterial1;
meshTask2.onSuccess = function (task) {
task.loadedMeshes[0].material = myMaterial2;
meshTask3.onSuccess = function (task) {
task.loadedMeshes[0].material = myMaterial3;

Finally I load the container.


Anyway - I guess to cut a long story short. What is the best way of loading 3 independent .stl files to a scene and assign a different material to each. I’m pretty sure that whilst the aboveworks this is not it!


If this code works for you I see no problems.
AssetsManager is very convenient when dealing with meshes and their transformations.
[0] will be always [0] because this is the first node of the mesh in every function call (I believe you have only 1 node in .stl file).

Callback is necessary here because one needs to be sure that material is assigned to the mesh after it was sucessfully loaded, otherwise the variable would be undefined.

Hi - Thanks for your comments. If you are happy that what I have done is acceptable as a practice then I will continue in this way moving forwards. Thanks again.

1 Like