Three.js场景移除对象报错:children[i] is undefined 解决求助
解决Three.js遍历移除对象时的TypeError问题
你遇到的报错是因为在traverse遍历场景节点的过程中直接调用scene.remove(child),修改了场景的子元素数组。traverse是按顺序遍历数组的,当你移除一个元素后,数组长度变短,后续遍历的索引会超出范围,导致找不到children[i]。
解决方案一:先收集待移除对象,再批量移除
这种方法不会干扰遍历过程,适用于需要深层遍历所有节点的场景:
removeLegoByPos = (pos) => { const toRemove = []; this.scene.traverse((child) => { if (child.isGroup && child.userData.position) { if (child.userData.position.equals(pos)) { toRemove.push(child); } } }); // 统一移除收集到的对象 toRemove.forEach(child => { console.log(child.name); this.scene.remove(child); }); }
解决方案二:反向遍历直接子元素
如果目标对象都是场景的直接子元素,不需要深层遍历,可以从后往前遍历数组,避免移除元素后索引错乱:
removeLegoByPos = (pos) => { // 从最后一个元素开始遍历,移除元素不影响前面的索引 for (let i = this.scene.children.length - 1; i >= 0; i--) { const child = this.scene.children[i]; if (child.isGroup && child.userData.position) { if (child.userData.position.equals(pos)) { console.log(child.name); this.scene.remove(child); } } } }
推荐使用第一种方案,它能处理目标对象在场景树任意层级的情况,且逻辑更稳妥。
内容的提问来源于stack exchange,提问作者Bilal
相关产品推荐
相关产品推荐

