You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Three.js 125版本中InstancedMesh实例无法设置颜色的问题求解

Three.js v125 InstancedMesh实例颜色不生效问题修复方案

核心错误点

  • 实例数量参数不匹配:初始化InstancedMesh时第三个参数设为1000,代表最大支持1000个实例,但你循环逻辑写的是i < 6000,超出上限的操作全部无效
  • 循环索引重复自增:for循环本身会自动执行i++,你在setMatrixAt(i++, o3d.matrix)行又手动对i做了自增,导致每次循环索引跳2,setColorAt的索引和矩阵索引不对应,还会快速超出实例数上限
  • 材质未开启实例颜色支持:MeshBasicMaterial默认不会读取实例颜色属性,需要手动开启vertexColors配置

修复后完整代码

addSphere(){
    var geometry = new THREE.SphereGeometry(0.5, 32, 32);
    // 新增vertexColors: true配置启用实例颜色支持
    let material = new THREE.MeshBasicMaterial({ 
        color: 0x8cde0d,
        vertexColors: true
    });
    // 实例数上限和后续循环数保持一致,这里改成6000匹配你原来的循环逻辑
    this.stars2 = new THREE.InstancedMesh(geometry, material, 6000);
    let o3d = new THREE.Object3D();
    let position = new THREE.Vector3();
    let color = new THREE.Color();
    this.stars2.instanceMatrix.setUsage( THREE.DynamicDrawUsage ); 

    for (let i = 0; i < 6000; i++) {
        const random = +(Math.random() * 10).toFixed(0);
        let colorValue = 0x8cde0d;           
        position.set(
            Math.random() * 800 - 500,
            Math.random() * 800 - 500,
            Math.random() * 800 - 500
        )
        o3d.position.copy(position)
        o3d.updateMatrix()
        // 去掉这里的i++,用当前循环的i即可
        this.stars2.setMatrixAt(i, o3d.matrix);

        // 三种写法都可以生效,这里保留你要用的随机色写法
        this.stars2.setColorAt(i, color.set(0xffffff * Math.random()));
    }
    this.stars2.instanceColor.needsUpdate = true;
    this.stars2.instanceMatrix.needsUpdate = true;
    this.scene.add(this.stars2);
}

补充说明

你之前写的三种setColorAt调用方式语法都是正确的,修复以上三个问题后均可正常生效。

内容的提问来源于stack exchange,提问作者user824624

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 06:54:04