Unable to change the material of a model on click of a button

Ii have been trying to change the color of the object that I have. For that I have created a button, which when clicked on should change the color. It is a very basic script but I getting an error called ‘Cannot read property ‘0’ of undefined’.

Here is my script

var BtnStates = pc.createScript('btnStates');

BtnStates.attributes.add('blue_mat', {
    type: 'asset',
    assetType: 'material'


// initialize code called once per entity
BtnStates.prototype.initialize = function() {
    // Get the original button texture
    this.originalTexture = this.entity.element.textureAsset;

    // Whether the element is currently hovered or not
    this.hovered = false;
    this.entity.element.on('mousedown', this.onPress, this);

BtnStates.prototype.onPress = function (event) {
    this.Rhino_model.meshInstances[0].material = this.blue_mat.resource;

I think you lost the context.

Try arrow function syntax instead of traditional.

I dont get you. what is the arrow function syntax. Is it this

if (event.key === pc.KEY_R && this.redMaterial) {
        this.entity.model.meshInstances[0].material = this.redMaterial.resource;

Oh, no.

You are trying to get instances of entity, not of model.
It should be

BtnStates.prototype.onPress = function (event) {
    this.Rhino_model.model.meshInstances[0].material = this.blue_mat.resource;

Still getting the same error

BtnStates.prototype.onPress = function (event) {
    this.Rhino_model.model.model.meshInstances[0].material = this.blue_mat.resource;


yeah. same thing with the given code

It was

and then

So try the last one, please.

I tried with both. Getting the same error

Gimme the link to your project.


Okay, you lied.


BtnStates.prototype.onPress = function (event) {
    this.Rhino_model.model.meshInstances[0].material = this.blue_mat.resource;

is working.
Don’t lie please.

The scene you provided is working fine.

It is still not working for me in the original scene

Just compare my script with yours one.

The only thing I changed was adding .model after Rhino_model.

Please tell us only truth. We still trust you, but it’s not unswervingly.

I’ll try copying your script into mine.


Can I say it’s solved?

Still Doesnt work for my scene

Umm no. I mean it is working for the scene you provided. I do not know what the difference is between your scene and mine

Okay, I see you changed your script, but profiler says you don’t.

Probably, your script file is cached somehow.

So should I delete this script and create a new one.