1

I have around 20k objects instanced like this:

<instancedMesh
      ref={meshRef}
      args={[null, null, events.length]}
      onPointerEnter={toggleHover}
      onPointerLeave={toggleHover}
      onClick={handleClick}
    >
      <sphereGeometry args={[1, 8, 8]} attach="geometry"></sphereGeometry>
      <shaderMaterial
        vertexShader={THREE.ShaderLib.lambert.vertexShader}
        fragmentShader={THREE.ShaderLib.lambert.fragmentShader}
        uniforms={uniforms}
        attach="material"
        lights
        vertexColors
      />
    </instancedMesh>

I then load the colors using a useEffect:

useEffect(() => {
    if (colors) {
      const colors_arr = new Float32Array(colors);
      const colorAttribute = new THREE.InstancedBufferAttribute(colors_arr, 3);
      meshRef.current.geometry.setAttribute("color", colorAttribute);
      meshRef.current.geometry.attributes.color.needsUpdate = true;
    }
  }, [colors]);

And then I try to update it with another useEffect:

useEffect(() => {
    // Set color of hovered event
    let colors_clone = colors.slice(0);
    if (hovering.current) {
      const hoveringClr = new THREE.Color("#FFFFFF");
      colors_clone[hovering.current * 3] = hoveringClr.r;
      colors_clone[hovering.current * 3 + 1] = hoveringClr.g;
      colors_clone[hovering.current * 3 + 2] = hoveringClr.b;

      document.body.style.cursor = "pointer";
    } else {
      document.body.style.cursor = "auto";
    }

    // Reset color of previous event
    if (hovering.previous) {
      const prevClr = getEventColor(hovering.previous);
      colors_clone[hovering.previous * 3] = prevClr.r;
      colors_clone[hovering.previous * 3 + 1] = prevClr.g;
      colors_clone[hovering.previous * 3 + 2] = prevClr.b;
    }

    setColors(colors_clone);
  }, [hovering]);

The hovering state updates the current hovered instance id and previous hovered instance id.

The colors are supposed to be set each time the array "colors" is updated, but it doesn't, except in the beginning. I thought that using the needsUpdate flag was enough, but it doesn't want to update.

I tried using useFrame by listening to changes of hovered (by comparing the previously hovered to the current and changing colors only then) but that still doesn't work. When I run this code it initially sets the colors correctly. But when I hover it doesn't change the colors.

0 Answers0