[SOLVED] Issue with passing dynamically created material to a dynamically attached script

Hi,

We ran into an issue with scripting as follows:
We are creating an entity at run-time and then attaching a script instance to it.
When we try to pass a material (which is also dynamically created previously), the newly created script instance does not receive the material and instead sees a null value.

Sample project here with relevant parts of code:
https://playcanvas.com/editor/project/918845

Console logs should show meshGenerator.initialize receiving handle to material with name: “mat-UVMap0.png” but receives null.

What are we doing wrong here? Is it to do with how we are declaring the attribute? (Material passed from Editor works fine though)

Thanks.

The issue is that the meshGenerator is expecting a material asset for materialK

MeshGenerator.attributes.add("materialK", {type: "asset", assetType: "material",title:"MaterialK"});

But createMapTexture is giving it a pc.StandardMaterial, not an asset

        //make a new material
        const material0 = new pc.StandardMaterial();

        //...
        //Binds texture to the box render
        box.script.create("meshGenerator", {
            attributes: {

                textures: boxTexture,
                materialK: material0 // This is a pc.StandardMaterial, not asset
            }
        });

Thanks @yaustar.

So is there a recommended way to pass the material to the script?

Or is it easier to pass an entity and let the script extract the material from it?

Thanks.

I would do it after the script is created for ease to be honest and perhaps call your own script init function.

eg

var scriptInstance = box.script.create("meshGenerator");
scriptInstance.materialK = material0;
1 Like

@yaustar : Thanks again.

That worked. We finally ended up using our own init function and passed the material manually.