Error while rotating an GLTF object from animate()

Hello!

It’s my first post here, and I’m very new to Three.js. Hope my question makes sense!

I loaded a GLTF object to my scene, but when I want to rotate it from the animate() function, I receive the following message in the console:

"Uncaught TypeError: Cannot read property ‘scene’ of undefined at animate"

After receiving this error, and having a black screen for some seconds, the scene appears with the object rotating. But as I want to do a loading page, this delay is bringing me troubles.

Here is how I load my object and the animation:

let objectSheep;

function addSheep() {

const loader = new GLTFLoader().setPath( 'models/' );
loader.load( 'sheep3.gltf', function (obj) {

    objectSheep = obj;
    
    objectSheep.scene.traverse( ( child ) => {
        if ( child.isMesh ) {
            child.material = materialSheep; 
            child.material.side = THREE.DoubleSide;}
    } );

    scene.add( objectSheep.scene );
} );

}

function animate() {
requestAnimationFrame( animate );
objectSheep.scene.rotation.y += 0.006;
render();
}

If anyone knows what is happening and how could I avoid receiving this error, would appreciate it very much!
Thanks!

Loading is asynchronous. If you start calling animate() before loader.load is finished - objectSheep will not be set yet, and it’s value will be undefined.

What you can do is add a conditional:

function animate() {
  requestAnimationFrame( animate );
  
  if (objectSheep) {
    objectSheep.scene.rotation.y += 0.006;
  }

  render();
}
1 Like

Oh great. Now makes a lot of sense, and it solved the issue.

Thank you so much @mjurczyk