Dynamic Material Update on Multiple Objects


#1

https://playcanvas.com/project/585973/overview/material-update-test

Hi - I am trying to update materials on multiple objects by loading the textures from remote URLs.

I am doing this all within the initialize function;

..prototype.initialize = function() {
//first image
this.app.assets.loadFromUrl(url, "texture", function(err, asset) {
        
        var image = asset.resource;
       //FirstBox is the entity to update (large box in scene)
        t.updateImage(FirstBox,image)
        
    }.bind(this), function (err) {
    console.error(err);
    });

//second image
this.app.assets.loadFromUrl(nurl, "texture", function(err, asset) {
       
        var image = asset.resource;
        //UnderBox is the entity to update (smaller box in scene)
        t.updateImage(UnderBox,image)
        
    }.bind(this), function (err) {
    console.error(err);
    });

...
}

...prototype.updateImage = function (ent,image) {
    ent.model.material.diffuseMap = image;
    ent.model.material.update();
};

However - the updateImage function is updating all of the objects’ materials instead of the entity on which it is called - so that all entities have the latest material that has been updated.

Is there a way to dynamically load textures for multiple objects this way?

Any help would be greatly appreciated!


#2

Try giving each object a separate material.


#3

Do you mean manually assigning a different material to each object before making the calls to ..loadFromUrl()?


#4

Hi Adrian,

Either give them different materials in the editor, or create the material at run-time.

I forked your project, you can see both ways here…
https://playcanvas.com/project/602904/overview/material-update-test-fork


#5

Thanks so much! Now I understand what you mean by updating with new material :slight_smile:

Thanks for the approach and code!