Three.js OBJLoader prevent double of assets

three.js OBJLoader .obj

When using the OBJLoader you have to relies on browser caching so that assets are not loaded multiple times and endure the fact that it has to be parsed multiple times

The following class will do this internally and you can call it as many times as you like.

The OBJLoaderHelper relies on the OBJLoader and does not replsce it.

class OBJLoaderHelper {

    constructor() {

        let manager = new THREE.LoadingManager()
        manager.onProgress = function(item, loaded, total) { console.log(item, loaded, total) }

        this.objLoader = new THREE.OBJLoader(manager)

    }

    get(modelpath, callback) {

        if (!this[modelpath]) {

            if (!this[modelpath + "waiting"]) this[modelpath + "waiting"] = []
            this[modelpath + "waiting"].push(callback)

            if (!this[modelpath + "loading"]) {
                this[modelpath + "loading"] = true
                let _self = this

                this.objLoader.load(modelpath, function(model) {
                    _self[modelpath] = model
                    _self[modelpath + "waiting"].forEach(c => c(model.clone()))

                    delete _self[modelpath + "loading"]
                    delete _self[modelpath + "waiting"]

                })

            }

        } else callback(this[modelpath].clone())

    }

}

and we would call it in this fashion

var material = new THREE.MeshStandardMaterial({ color: 0x000000 })

objLoaderHelper.get('models/streetlight.obj', function(lamp) {

    lamp.traverse(function(child) {
        if (child instanceof THREE.Mesh) child.material = material
    })

    scene.add(lamp)

})

Reference

OBJLoader on Github github.com

History Feb 19, 2017