Create Entity and Assign Texture at runtime

I’m trying to assign a material at runtime. I’ve created two material assets and assigned as attributes to the script “logic”. When I run the scene I still see the default material.

var logic= pc.createScript('logic');

logic.attributes.add('materials',{ type:'asset',assetType:'material', array:true});


// initialize code called once per entity
GameLogic.prototype.initialize = function() {
    
        var entity = new pc.Entity();
        entity.addComponent("model",{type:'box',});
        material = entity.model.meshInstances[0].material;
        material=this.materials[0].resource;
        this.app.root.addChild(entity);
    }
    

What am I missing? Thank you.

Hi @noah_mizrahi,

You are accessing the Playcanvas api correctly, the thing you are missing is assigning the material at the right place. Something like this I feel should work for you:

       var entity = new pc.Entity();
       entity.addComponent("model", { type: "box" });
       entity.model.meshInstances[0].material = this.materials[0].resource;
       this.app.root.addChild(entity);

aha, makes sense since the material variable is a copy not a pointer.

Is there a way to create a variable which is a pointer to a parameter and not a copy?

Actually most variable assignments in Javascript are done by reference. Only a handful of types are copied by value (number, string, null etc).

In your example your first material assignment references the currently assigned material of the meshInstance, not to the material property of the meshInstance.

The way to do it using your assignments would be like this:

meshInstance = entity.model.meshInstances[0];
meshInstance.material = this.materials[0].resource;

Thank you.