Cannot set property map of undefined with GLTF Loader

Im trying to add texture to a glb model, but i keep getting said error. What have i done wrong?
** line is failing
Excerpt:

var loader = new THREE.GLTFLoader();

loader.load(

    'models/animated_arrow.glb',

    function (gltf) {

        mesh = gltf.scene;

        mesh.scale.set(1, 1, 1);

        mesh.position.set(4.6, 0, 1);

        mesh.rotation.set(1.575, 0, 0);

        scene.add(mesh);

    },

);

var textureLoader = new THREE.TextureLoader();

textureLoader.load('./img/AnimatedArrow.png', function ( map ) {

    **mesh.material.map = map;**

    mesh.material.map.encoding = THREE.sRGBEncoding;

    mesh.material.map.flipY = false;

});

There are two likely problems here – one, the texture may be loading before the model, in which case mesh will not be defined when you try to assign it a texture. Two, the model probably contains more than just a single mesh, in which case the root object may not be a mesh itself. Try:

var texture = textureLoader.load('./img/AnimatedArrow.png', function ( map ) {
  map.encoding = THREE.sRGBEncoding;
  map.flipY = false;
} );

gltfLoader.load( 'models/animated_arrow.glb', function ( gltf ) {

  var model =  gltf.scene;
  model.scale.set(1,1,1);
  // ... set position, rotation, scale...

  model.traverse( function ( object ) {
    if ( object.isMesh ) object.material.map = texture;
  } );

  scene.add( model );

});


1 Like