How to change the material correctly

Hi. Help me solve the problem. I have an array of materials. I need to apply them to game objects.When I change the texture, all objects have the same textures

forEach((elem,i)=>{
    var newEl = el.clone()
    newEl.name = 'BoxTemplate'+ i
    newEl.rigidbody.teleport(0,0,5)
    this.app.root.addChild(newEl)
    newEl.model.meshInstances[0].material.diffuseMap = this.app.textureItem[i]
    newEl.model.meshInstances[0].material.update()
})

in this code, I change textures, and I also have materials

Hi @sergey_ch,

To update the material you use the following line, no need for calling .update() unless you are changing a material property:

newEl.model.meshInstances[0].material = newMaterial;

When I try to do this, I get errors:
Uncaught TypeError: Cannot read property ‘cull’ of undefined

 const newMaterial = this.app.material[i]
  newEl.model.meshInstances[0].material = newMaterial

Если не трудно, можешь посмотреть в редакторе? ссылку в личку пришлю

newMaterial was just an example variable. You need to replace that variable with the materials you keep in your materials array.

I did it.

const newMaterial = this.app.material[i]
1 Like

Try debugging then if the following is an actual material using the browser console:

const newMaterial = this.app.material[i];
console.log(newMaterial);

Did, it’s standartmaterial, and it’s weird

it generates an error endlessly. Look in the editor, I sent the link

First of all one good advice is avoid spamming the pc.Application reference, since you may override required properties. For example instead of doing the following in your scripts:

    this.app.level = 1
    this.app.state = null

Just do this:

    this.level = 1
    this.state = null

The error that you get indicates that somewhere you passed undefined/null for material, check your loop again. I did take a look but it’s too much code to debug like that:

image

Figured out the error cycle. Put an insert of the primitive after the assignment of the material. Now here is such a mistake. You don’t know what that means?
Cannot read property ‘blendType’ of undefined

Yes, that means that a material you pass to a mesh instance is undefined.