Hello Everyone,
Currently I am working on feature in which based on distrance certain group of meshes will disappear as it they move far away from camera. I am attaching my code it is working as it is expected to be but its droping frame rate to 20 from 45~50 fps. How i can optimize it
if (sceneRef && visible) {
getStreetPins();
if (pins && customControls?.current?.camera.position) {
if (customControls?.current?.camera.position.distanceToSquared(pins?.parent.position)! < 4000) {
const currentPin = sceneRef.current.getObjectByName(`StreetPin_${id}`);
if (!currentPin?.visible) {
currentPin.visible = true;
}
} else {
const currentPin = sceneRef.current.getObjectByName(`StreetPin_${id}`);
if (currentPin?.visible) {
currentPin.visible = false;
}
}
}
}
- This is what you’re calling when you’re calling
scene.getObjectByName
(assuming this sceneRef
is pointing to the top-most Scene.) You’re basically traversing everything - which can be expensive if (a) there’s a lot of stuff in your scene, or (b) you call it very often. The one and only way of optimising it is to limit the search - for ex. by caching the results, instead of using getObjectByName, create a hashmap that maps street pins to objects directly, ex:
const nameToObjectMap = {
StreetPin_1: new Object3D(),
StreetPin_2: new Object3D(),
// ...
StreetPin_N: new Object3D()
};
Then you can place the pins in the scene using <primitive object={...} />
, and retrieve using the hashmap directly - nameToObjectMap["StreetPin_" + id]
- that reduces the complexity of traversing the entire scene top-to-bottom, to just reading a single prop of the hashmap.
- You can check which functions take how much time in Performance tab in Chrome devtools.
1 Like
Thanks for your reply its very helpful. but currently i am using useGLTF method to seprate out nodes and material from the Object3d and using it as meshes and manuplating its material can you help me in that context
Why do you need to traverse scene imperatively if you load models reactively? Just use react state directly in components for calculations.
1 Like
Got the solution. Thank alot buddy for help