BufferGeometryUtils.mergeBufferGeometries合并模型時有可能出現:three.module.js:11217 Uncaught TypeError: Cannot read property 'isBufferGeometry' of null
此時我們可以先使用BufferGeometry轉Geometry合并模型然後再轉BufferGeometry方式
以下方式解決這個問題代碼
function merge(object) {
const geometries = [];
const matArr = [];
var meshs = new THREE.Geometry();
object.traverse((obj) => {
const child = obj;
if (child.isMesh) {
const geo = child.geometry.clone();
if (Array.isArray(child.material)) {
child.material = child.material[0];
}
matArr.push(child.material);
geo.index = null;
child.updateWorldMatrix(true, true);
geo.applyMatrix4(child.matrixWorld);
geometries.push(geo);
}
});
for(var i=0; i<geometries.length; i++){
meshs.merge(new THREE.Geometry().fromBufferGeometry( geometries[i] ), new THREE.Geometry().fromBufferGeometry( geometries[i] ).matrix, i);
}
var buffermeshs = new THREE.BufferGeometry().fromGeometry(meshs);
const result = new THREE.Mesh(buffermeshs,matArr);
console.log(result)
return result;
}
以下是直接合并BufferGeometry模型的方式
function merge(object) {
const geometries = [];
const matArr = [];
object.traverse((obj) => {
const child = obj;
if (child.isMesh) {
const geo = child.geometry.clone();
if (Array.isArray(child.material)) {
child.material = child.material[0];
}
matArr.push(child.material);
geo.index = null;
child.updateWorldMatrix(true, true);
geo.applyMatrix4(child.matrixWorld);
geometries.push(geo);
}
});
console.log(geometries);
const buffergeo = BufferGeometryUtils.mergeBufferGeometries(
geometries,
true
);
console.log(buffergeo);
const mesh = new THREE.Mesh(buffergeo, matArr);
return mesh;
}