Hi,
I’m a total newbie in React and Babylon.js, so apologies in advance if this is something completely obvious.
I’m doing a small app that highlights meshes in a scene. I was able to do that easily, by casting a ray and then highlighting the mesh via HighlightLayer.
In order to unhighlight the mesh, I’ll need to check if it’s highlighted first, so I created a pickedObjects state in React:
const [pickedObjects, setPickedObjects] = useState([]);
The scene’s onPointerDown handler is a function that does the ray casting, and highlights or unhighlights the mesh.
The problem is that for some reason, calling setPickedObjects from the onPointerDown handler doesn’t change the state at all.
If I do:
function addToPicked() {
console.log("Setting picked objects");
setPickedObjects((oldPickedObjects) => [...oldPickedObjects, "AAA"]);
console.log("PickedObjects length = " + pickedObjects.length);
for (let i = 0; i < pickedObjects.length; i++) {
console.log("Obj #" + i + " = " + pickedObjects[i]);
}
}
and set the scene’s onPointerDown handler to addToPicked:
scene.onPointerDown = addToPicked;
the handler is called but the pickedObjects state never is updated:
Setting picked objects
PickedObjects length = 0
If I create a simple html button and set its onClick handler to AddToPicked, then everything works as expected, and I get the output:
Setting picked objects
PickedObjects length = 0
Setting picked objects
PickedObjects length = 1
Obj #0 = AAA
Setting picked objects
PickedObjects length = 2
Obj #0 = AAA
Obj #1 = AAA
Is there anything I need to do, when updating a React component’s state from a Babylon.js handler?
Thanks in advance,
Alex