[SOLVED] Did not manage to change material from array

i try to make an array of materials as an attribute.
there is an index attribute and i wanna set the material to be array[index]

this is the project

and that’s the code in the script “ChangeTexture”

var ChangeTexture = pc.createScript('changeTexture');

ChangeTexture.attributes.add("materials", {
    type: "asset",
    assetType: "material",
    array: true,
    title: "List Of Materials",

ChangeTexture.attributes.add('currentMaterial', {type: 'number', default: 0});

// initialize code called once per entity
ChangeTexture.prototype.initialize = function() {

    var material = this.entity.model.meshInstances[0].material = this.materials[this.currentMaterial];


the last line generates an error:

[playcanvas-stable.dbg.js:14415]: Cannot read property ‘push’ of undefined

TypeError: Cannot read property ‘push’ of undefined
at MeshInstance.set (https://code.playcanvas.com/playcanvas-stable.dbg.js:14415:36)
at script.ChangeTexture.initialize (https://launch.playcanvas.com/api/assets/files/changeTexture.js?id=21644384&branchId=60313b67-c545-40e5-bb9d-11dedfdfd8f2:19:64)
at ScriptComponent._scriptMethod (https://code.playcanvas.com/playcanvas-stable.dbg.js:27191:21)
at ScriptComponent._onInitialize (https://code.playcanvas.com/playcanvas-stable.dbg.js:27209:16)
at ScriptComponentSystem._callComponentMethod (https://code.playcanvas.com/playcanvas-stable.dbg.js:27609:51)
at ScriptComponentSystem._onInitialize (https://code.playcanvas.com/playcanvas-stable.dbg.js:27614:10)
at Function._helper (https://code.playcanvas.com/playcanvas-stable.dbg.js:24308:14)
at Function.initialize (https://code.playcanvas.com/playcanvas-stable.dbg.js:24311:10)
at Application.start (https://code.playcanvas.com/playcanvas-stable.dbg.js:23734:24)
at https://launch.playcanvas.com/editor/scene/js/launch.js:7136:25

Error loading scripts. Open the browser console for details.

I did assign materials to the array in the inspector.
what am i missing?

You have an array of material assets rather than materials.


    var material = this.entity.model.meshInstances[0].material = this.materials[this.currentMaterial].resource;
1 Like

gatcha, worked, thanks

is there an option to have an array of materials?
or only material asset is valid?

An array of materials set in the Editor would assume that all the materials are ready by the time the app starts which isn’t always true. The asset system wraps this so you have can store a reference to the asset and access the resource once it has been loaded.

In a nutshell, it’s better to have an array of material assets rather than materials in this case.

1 Like