问题
I'm still pretty new at Three.JS, I'm pretty happy where I have gotten so far, but just need some help.
I have an GLTF object loaded into the scene, I want to be able to load different textures onto the object on the website by the user selecting a style, (like a customization feature).
Below is my code, at the moment it outputs nothing and I get the following error:
In Chrome:
"TypeError: Cannot set property 'map' of undefined"
In Firefox:
"TypeError: model.material is undefined"
var textureLoader = new THREE.TextureLoader();
var texture = textureLoader.load('../gtf/green/green.png');
texture.flipY = false;
var loader = new THREE.GLTFLoader();
loader.load( '../gtf/Box.gltf', function ( gltf ) {
model = gltf.scene;
scene.add( model );
});
model.material.map = texture;
Any help would be greatly appreciated.
回答1:
The function loader.load()
runs asynchronously and you don't have the model
variable immediately set after you call it. So the solution you are looking for is to move the model.material.map = texture;
inside the callback function, like this:
loader.load( '../gtf/Box.gltf', function (gltf) {
model = gltf.scene;
texture.flipY = false; // for glTF models only
model.material.map = texture; // <-- move here
scene.add( model );
});
This will guarantee that you have a valid model
object that you can use.
回答2:
The problem that you are running into is that the scene that you have assigned as model
contains a lot more information than just the mesh and material information. You will need to iterate over the scene object model
in order to find the mesh, and then change the material accordingly. While the initial data format that you are using is different, the answers you are looking for can be found in a previous post here:
Change texture of loaded .obj in three.js at runtime
Edit:
@HugoTeixeira is right that assignment of the texture needs to be moved into the callback function of loader.load()
(sorry, I totally overlooked this previously), but the actual assignment model.material.map = texture;
isn't going to work. You will still need to iterate over the gltf.scene
object as mentioned above in order to find the mesh that you want to assign the texture to.
来源:https://stackoverflow.com/questions/52067999/import-another-texture-at-runtime-within-three-js-and-gltf