[SOLVED] Animation not playing with script

Hi! I am trying to play an animation with a button click. The animation is such that when it plays, the button has to be disabled and after the animation, the button has to be enabled. The button works perfectly with the enabling and disabling. But the animation gives error when the button is pressed.

Here is the code:

var ButtonPress = pc.createScript('buttonPress');

ButtonPress.attributes.add('animation',{type:"asset", assetType:"animation"});
// initialize code called once per entity
ButtonPress.prototype.initialize = function() {
    
    this.model = this.entity.findByName("Product");

    var self = this;
    
    this.entity.button.on('click', function(event) {
        self.playAnimation();
    }, this);
};

ButtonPress.prototype.playAnimation = function() {
    this.entity.button.enabled = false;
    this.entity.animation.play('Scene.glb');
    this.entity.button.enabled = true;
};

And here is the error thrown after the button is pressed:
Uncaught TypeError: Cannot read properties of undefined (reading 'play')

Hi @Rushil_Sojitra,

Are you using the new anim component in your entity? Or the older animation one?

If it’s former then you need to use the .anim namespace to control your animation. Check this example on how to setup and play an animation using the anim state graph:

https://developer.playcanvas.com/en/tutorials/anim-blending/

1 Like

Hi @Leonidas ! I followed the tutorial you sent and used the anim state graph. I tried to launch after making the changes, but it gives me this error :
Uncaught TypeError: Cannot read properties of undefined (reading 'setBoolean')

Here is the changed code:

var ButtonPress = pc.createScript('buttonPress');

//ButtonPress.attributes.add('animation',{type:"asset", assetType:"animation"});
// initialize code called once per entity
ButtonPress.prototype.initialize = function() {
    
    var self = this;
    
    this.entity.button.on('click', function(event) {
        self.playAnimation();
    }, this);
};

ButtonPress.prototype.playAnimation = function() {
    this.entity.button.enabled = false;
    this.entity.anim.setBoolean('play', true);
    this.entity.button.enabled = true;
};

Are you sure this script is attached on the entity that holds the anim component?

Seems like the entity this script is executing on doesn’t have that, hence the undefined error.

1 Like

Actually I have attached this script to the button entity. Do I need to attach it to the entity with the anim component?

Not necessarily, but you need to adjust your code to find and execute your code on the entity that has the anim component.

Example way to do it, let’s say your entity is named ‘Player’:

this.app.root.findByName('Player').anim.setBoolean('play', true);
2 Likes

It works! Thank you very much for your help @Leonidas !!

1 Like