Unable to play animations from code

https://playcanvas.com/editor/project/1440799

Hi there!

I’ve been struggling to get animations to play.

I’ve read the documentation but I don’t think I’m quite doing it right.

I’ve created a glb with an animation. I’ve looked at it in a model view to confirm the animation plays (animation preview in pc does not currently work).

I’ve created a state called State1 and set Start to transition to it.

in short I call: this.anim.baseLayer.play(stateName);

Currently nothing plays. There have been assets that this code has worked on but in general nothing plays.

Any ideas what I’m doing wrong?

var AnimTester = pc.createScript('animTester');

AnimTester.prototype.initialize = function () {
    this.anim = this.entity.anim;
    if (!this.anim) {
        console.warn('[AnimTester] No Anim component found on', this.entity.name);
        return;
    }
    if (!this.anim.baseLayer) {
        console.warn('[AnimTester] Anim component has no baseLayer on', this.entity.name);
        return;
    }

    // Make sure the Anim component is actually running
    this.anim.playing = true;

    // Listen for spacebar
    this.app.keyboard.on(pc.EVENT_KEYDOWN, this.onKeyDown, this);

    // Clean up when entity is destroyed
    this.on('destroy', function () {
        this.app.keyboard.off(pc.EVENT_KEYDOWN, this.onKeyDown, this);
    }, this);
    
    console.log('[AnimTester] ✅ Initialized - press SPACEBAR to play "State1"');
};

AnimTester.prototype.onKeyDown = function (e) {
    if (e.key !== pc.KEY_SPACE) return;
    if (!this.anim || !this.anim.baseLayer) return;

    var stateName = 'State1';
    
    // Check if state exists in controller
    var controller = this.anim.baseLayer._controller;
    if (controller && controller._states && !controller._states[stateName]) {
        console.error('[AnimTester] ❌ State "' + stateName + '" not found in state graph!');
        console.log('[AnimTester] Available states:', Object.keys(controller._states));
        return;
    }
    
    // Play that state on the base layer
    this.anim.baseLayer.play(stateName);
    console.log('[AnimTester] ✅ Playing state:', stateName);
};

Hi @noah_mizrahi !
I think you should base your code off of this: Anim State Graph Blending | PlayCanvas Developer Site
Based off the code I have used in the past for animation, this works better.

Is the animation working without the script? If not, the issue is likely in your setup or the animation itself.

Thanks! I can try parameters but have you had any luck playing specific anim state with code?

Yes, well I can’t preview in PC but I can load it in a model viewer and see the animation run.

As far as I can see, your setup looks correct, so the animation should play on start without using the script. I suspect something is going wrong during import, possibly bone naming or a similar issue. The topic below might help.

Thanks man