Change color of material is effecting all objects

Hey guys, I am currently trying to change the color of a material by way of cloning which I read is the right approach. I have it working for some of my models but not all of them. The only difference being the way that the models materials are accessed.

This works for another model I’m adding variation to where the target material is in the first children array. However for my tree model, the material I need access to is in the second children array. I am able to change the color so I can confirm that this is the right target.

So the way this works is, when a new tile spawns, I call changeColor on my trees which will change their leaves green tint slightly so the trees don’t all look the same. This works initially, but as soon as a new tile spawns, all trees in play change color at the same time. The tree color should only change when a new tile spawns, and only the trees on the new tile should be changing.

I’m guessing it is related to my target or how I am going about cloning and creating values. But this is the code in question.

 changeColor(){

    var target = this.model.scene.children[0].children[1];

    var newColor = target.material.color;
    newColor.g = Utils.getRandomFloat(this.treeGreenIntensityMin, this.treeGreenIntensityMax);

    var newMat = target.material.clone();
    newMat.color.set(newColor);

    target.material = newMat;

}

Thanks guys!

var newColor = target.material.color.clone();
2 Likes

I can’t believe I was this close! This did the trick, thanks man!

Glad, it worked out for you.
Here is how I would have done it in JS.

Show me

// assuming model, t…Max, and t…Min are global.
// assuming t…Max and t…Min are >= 0 && <= 1

function changeColor(){

var mesh = model.scene.children[0].children[1];

if( ! mesh.material.is_cloned ) {
mesh.material = mesh.material.clone();
mesh.material.is_cloned = 1; }

mesh.material.color.g = treeGreenIntensityMin + Math.random() * (treeGreenIntensityMax - treeGreenIntensityMin);
}