Play animation once (no anim state graph)

How can I play an animation once?
The code I have works with a looping animation, but not when I do not want it to loop. The animation simply doesn’t play.

AnimateCommand.attributes.add('object', {type: 'entity'});
AnimateCommand.attributes.add('animation', { 
    type: 'json', 
    title: 'Animation Asset',
    schema: [{
        name: 'stateName',
        title: 'State Name',
        type: 'string',
    }, {
        name: 'asset',
        title: 'Asset',
        type: 'asset',
        assetType: 'animation'
    }]
});
AnimateCommand.attributes.add('delay', {type: 'number', title: 'Delay in seconds'});

AnimateCommand.prototype.initialize = function() {
    //works when last parameter is 'true'
    this.object.anim.assignAnimation(this.animation.stateName, this.animation.asset.resource, 1, false); 
    this.object.anim.speed = 0;
};

AnimateCommand.prototype.execute = function() {
    setTimeout(() => {
        this.object.anim.baseLayer.play(this.animation.stateName);
        this.object.anim.speed = 1;
    }, this.delay * 1000);
};

Can you provide a public project example please?

The project is here: PlayCanvas | HTML5 Game Engine
Take a look at the “Instructor” scene, and press 2 to focus on the colored cube. The topright blue cube should begin to animate, but it only does so when I set it to loop in the code. (see Processes/Process 1/Step 2/Animate Command for the object with the script that controls it)

EDIT: Perhaps an issue with the anim.assignAnimation() function? I noticed a bug where I couldn’t assign multiple animations if I provide the optional parameters for speed and loop, but it works when I remove them (despite having used the default parameters). I’m not sure if the issues are related.

The issue was that the wrong number of parameters were used for assignAnimation

loop is the fifth param but you were sending it as the fourth param

    this.object.anim.assignAnimation(this.animation.stateName, this.animation.asset.resource, 1, false); 

So false is being set as speed for the state which is why it wasn’t animating.

It should be:

    this.object.anim.assignAnimation(this.animation.stateName, this.animation.asset.resource, null, 1, false); 
1 Like

Ah, okay. That explains a lot. The intellisense told me I was editing the speed and loop parameters, so I blame the IDE :stuck_out_tongue:

Thanks for pointing it out.

The intellisense thought the object was a AnimComponentLayer and not an AnimComponent.

Without hints, it has trouble understanding what the type is of script attribute so it just guesses.

Here it is with hints:

1 Like

here is something I have used and its working great