Hi, I create instance all by use gltfjsx.I don’t know how to do it, I need to generate 10 instances.Cube with different colors.Please help.
Here is link
import React, { useRef, useMemo, useContext, createContext } from "react";
import { useGLTF, Merged } from "@react-three/drei";
const context = createContext();
export function Instances({ children, ...props }) {
const { nodes } = useGLTF("/magicCube0622.glb");
const instances = useMemo(
() => ({
Arrow: nodes.arrow1,
Cube: nodes.cube,
}),
[nodes]
);
return (
<Merged meshes={instances} {...props}>
{(instances) => (
<context.Provider value={instances} children={children} />
)}
</Merged>
);
}
export function Model(props) {
const instances = useContext(context);
return (
<group {...props} dispose={null}>
<instances.Arrow />
<instances.Cube />
</group>
);
}
drcmda
June 23, 2023, 8:22pm
2
with the color property. <SomeInstance color="red" />
import React, { useRef, useMemo, useContext, createContext } from "react";
import { useGLTF, Merged } from "@react-three/drei";
const context = createContext();
export function Instances({ children, ...props }) {
const { nodes } = useGLTF("/magicCube0622.glb");
const instances = useMemo(() => {
const cubeInstances = Array.from({ length: 10 }, (_, index) => {
const cubeNode = nodes.cube.clone();
cubeNode.material = cubeNode.material.clone(); // Clone the material to avoid sharing
cubeNode.material.color.set(getRandomColor()); // Set a random color for each instance
return cubeNode;
});
return {
Arrow: nodes.arrow1,
Cube: cubeInstances,
};
}, [nodes]);
return (
<Merged meshes={instances} {...props}>
{(instances) => (
<context.Provider value={instances} children={children} />
)}
</Merged>
);
}
export function Model(props) {
const instances = useContext(context);
return (
<group {...props} dispose={null}>
{instances.Cube.map((CubeInstance, index) => (
<CubeInstance key={index} />
))}
<instances.Arrow />
</group>
);
}
function getRandomColor() {
// Generate a random RGB color
const r = Math.random();
const g = Math.random();
const b = Math.random();
return `rgb(${r}, ${g}, ${b})`;
}
Hope this help you.
Hi, Drcmda,
neciszhang:
<instances.Cube />
`<instances.Cube color=‘red’ /> doesn’t work.
Here is codesandbox link, can you help me to see this?
Hi, it doesn’t work, nodes.cube is PositionMesh. it’s not include material.
Here is codesandbox link
Yes, this works. I changed the color of the model to white to make it work. If the material is black, it doesn’t work with this.