Problems with tween material implementation: Cannot read properties of undefined (reading 'clone')

Hey everyone!
I’m following this Tween example for changing material color PlayCanvas | HTML5 Game Engine and trying to replicate the code to my own project.
So, I have a script that receives the reference for an entity from my scene that have 5 child objects which are the ones I’m gonna change the color. I called this referenced parent entity inside the script as closedPartsRoot.
Then, following the same thing as the Tween Material example script, on my Initialize function I’m using:

this.initalMaterial = this.closedPartsRoot.children[0].render.material.clone();

to have an initial copy of the material of the first child from closedPartsRoot. I used a console.log after this line to print the name of what was stored inside this.initialMaterial and got as the response the name of the material I was expecting (MT_Body), so everything’s alright until here.

Then, on my onPartClicked function I’m doing this:

// if already tweening then stop first
if (this.tween) {
        this.tween.stop();
}

this.tweenedProperties = {
        diffuse: this.standardColor.clone() //standardColor is an input on my script which is correctly assigned with an RGB value
};

// reset material
this.meshToHighlight = this.closedPartsRoot.children[0];
console.log('INITIAL MATERIAL: ' + this.initalMaterial + ' | ' + this.initalMaterial.name); // this prints [object Object] | MT_Body (the name is correct)
this.meshToHighlight.render.material = this.initialMaterial.clone(); //that's the line where I'm getting the error
this.meshToHighlight.render.material.diffuse = this.standardColor;
this.meshToHighlight.render.material.update();

// create a new tween using script attributes
this.tween = this.app.tween(this.tweenedProperties.diffuse)
        .to(this.highlightColor, 0.35, pc.SineInOut)
        .loop(false)
        .yoyo(true)
        .repeat(4);
    
// update diffuse on each tween update
    this.tween.on('update', function() {
        this.closedPartsRoot.children[0].render.material.diffuse = this.tweenedProperties.diffuse;
        this.closedPartsRoot.children[0].render.material.update();
    }.bind(this));

// start the tween
    this.tween.start();

What am I missing to be having this “Cannot read properties of undefined (reading ‘clone’)”?

You have a typo. Look at the following lines/variable names you are using

this.initalMaterial.name
this.initialMaterial.clone()

Do you see the difference in the property names you are using?

2 Likes