GLTFLoader OOP Pattern

The snippet above will return an initially empty scene, and that Scene will have content added to it as the content loads. If you want to wait for the content to be fully loaded before appending anything, you could use a callback, promise, or async/await. Most applications only need very simple caching, and even a factory/OOP pattern feels like overkill if you’re only dealing with 3-4 models. I would suggest trying something simple and letting us know if you have trouble.

var models = {};

function loadModel ( url ) {

  if ( models[ url ] ) {
    return models[ url ].then( ( o ) => o.clone() );
  }

  return models[ url ] = new Promise( ( resolve, reject ) => {
    loader.load( url, function ( gltf ) {
      resolve( gltf.scene );
    }, undefined, reject );
  } );

}

Also note that if you’re going to have the same model in the scene multiple places at the same time, you should probably clone it.

EDIT: Updated to handle multiple requests during initial load.

2 Likes