How can I share a material among different objects? #2790
-
Hello, I'm trying to save resources by sharing a single material across multiple objects. I tried to use the pattern below, but it does not work: the material is not rendered. I know how I would approach this in vanilla Three.js but am stumped for how to do it with R3F. I'd appreciate any help or tips, thanks!
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
I'd make sure that const MyCustomMaterial = React.forwardRef(function MyCustomMaterial(props, ref) {
return <myCustomMaterial {...props} ref={ref} />
}) Alternatively, you can share an instance from global scope among multiple meshes: const material = new MyCustomMaterial() // vanilla class
function Model() {
return (
<>
<Sphere args={[1, 32, 32]} material={material} />
<Plane args={[2, 2]} position={[3, 0, 0]} material={material} />
<Torus args={[1, 0.5, 32, 32]} position={[-3.5, 0, 0]} material={material} />
</>
)
} |
Beta Was this translation helpful? Give feedback.
-
Thanks so much for the help. I figured out what the issue was. I'm creating custom materials using the
I found that if I created a shared material using a forward ref like you outlined above, I would get this error:
The culprit, it turns out, was initializing the material uniforms in the component's return statement, if I return the material like this and initialize the uniforms after the material mounts, the error goes away and the sharing works perfectly:
Hope this helps someone who ran into the same problem. |
Beta Was this translation helpful? Give feedback.
Thanks so much for the help.
I figured out what the issue was. I'm creating custom materials using the
three-custom-shader-material
package, and the components are usually returned like this:I found that if I created a shared material using a forwar…