简体   繁体   中英

three.js — How do I select mesh outside of loader?

I want to change the material of a mesh which I can easily do within three.js 's mesh loader. However, once the loader is complete, I can no longer access it from an external function. It must be a scoping issue that I haven't been able to figure out.

This works (But I can't use it this way):

var loader = new THREE.GLTFLoader();
    loader.load('model.glb', function (gltf) {
    scene.add(gltf.scene);

    // Material changed below
    var newMat = new THREE.TextureLoader().load(something.jpg);
    gltf.scene.traverse(function (node) {
            node.material = newMat;
    });

});

This doesn't. How can I fix it?

var loader = new THREE.GLTFLoader();
loader.load('model.glb', function (gltf) {
    scene.add(gltf.scene);
});

function textureSwap(){
    var newMat = new THREE.TextureLoader().load(something.jpg);
    gltf.scene.traverse(function (node) {
            node.material = newMat;
    });
}

textureSwap();  // Material should change when calling this

The error is 'gltf is not defined'.

The error is 'gltf is not defined'.

This happens because gltf is only valid within the onLoad() callback. You can easily avoid the runtime error by assigning gltf.scene to a variable like model which is declared in a higher scope.

var model;

var loader = new THREE.GLTFLoader();
loader.load('model.glb', function (gltf) {
    scene.add(gltf.scene);
    model = gltf.scene;
});

function textureSwap(){
    var newMat = new THREE.TextureLoader().load(something.jpg);
    model.traverse(function (node) {
        node.material = newMat;
    });
}

You have to ensure that textureSwap() is only called after the loading process has finished. To make the function more robust, you can do this:

function textureSwap(){
    if ( model ) {
        var newMat = new THREE.TextureLoader().load(something.jpg);
        model.traverse(function (node) {
            node.material = newMat;
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM