threejs 删除模型,释放内存

2023-05-28  本文已影响0人  时间煮鱼
// 优化删除模型
    removeModel(parentGroup, group){
      parentGroup.remove(group);
      if (!this.$isEmpty(group)) {
        group.traverse(child => {
          if (child instanceof THREE.Mesh || child instanceof THREE.Line) {
            this.disposeMaterial(child.material);
            child.geometry.dispose && child.geometry.dispose();
          } else  {
            this.disposeMaterial(child.material);
          }
        });
        group = null;
      }
    },
    // 自己写的材质贴图释放
    disposeMaterial(material) { 
      if (material instanceof THREE.Material) {
        for (const value of Object.values(material)) {
          if (value instanceof THREE.Texture) {
            value.dispose();
          }
        }
        if (material.uniforms) {
          for (const value of Object.values(material.uniforms)) {
            if (value) {
              const uniformValue = value.value;
              if (uniformValue instanceof THREE.Texture) {
                uniformValue.dispose();
              }
              if(Array.isArray(uniformValue)){
                uniformValue.length = 0;
              }
            }
          }
        }
        material.dispose();
      }
    },
上一篇 下一篇

猜你喜欢

热点阅读