使用@react-three/csg时遇TypeError: Cannot read 'count'属性问题求助
使用@react-three/csg求几何体交集时的"TypeError: Cannot read properties of undefined (reading 'count')"解决方法
问题原因
你在<Base>和<Intersection>组件内部嵌套了完整的<mesh>(包含geometry和material),但@react-three/csg的CSG操作仅需要直接传入几何体对象,外层的<mesh>会封装几何体,导致CSG无法正确提取几何体数据,进而抛出读取undefined的count属性的错误。
修正后的代码
"use client"; import { Canvas } from "@react-three/fiber"; import { OrbitControls } from "@react-three/drei"; import { Base, Geometry, Intersection } from "@react-three/csg"; export default function Home() { return ( <main className="flex min-h-screen flex-col items-center justify-between p-24"> <Canvas> <ambientLight /> <OrbitControls /> <pointLight position={[10, 10, 10]} /> <mesh> <meshNormalMaterial /> <Geometry> <Base> <group position={[0, -1, 0]} rotation={[0, 45, 0]}> <boxGeometry args={[1, 1, 3]} /> </group> </Base> <Intersection> <group position={[0, -1, 0]} rotation={[Math.PI/2, 0, 0]}> <cylinderGeometry args={[0.5, 0.5, 3, 32]} /> </group> </Intersection> </Geometry> </mesh> </Canvas> </main> ); }
关键注意事项
- CSG组件(
Base、Intersection、Union、Subtraction)内部只能包含几何体或带有几何体的group,不能包含完整的<mesh>组件,CSG需要直接操作原始几何体数据。 - 旋转角度推荐使用弧度值(如
Math.PI/2代替90),Three.js底层基于弧度计算,避免角度转弧度的潜在问题。 - 外层
<mesh>已设置材质,内部无需重复添加material,CSG生成的最终几何体会复用外层材质。
内容的提问来源于stack exchange,提问作者user3479219
相关产品推荐
相关产品推荐

