three.jsdat.gui

Updating three.js texture throughthe dat.gui dropdown


I have loaded different textures using textureLoader and I am trying to update them using dat.gui controls.

Why is the code below not working?

gui.add(mesh.position, "y", -1, 1, 0.1);
gui.add(mesh.material, "map", { alpha: alphaTexture, color: colorTexture, normal: normalTexture })
    .onChange(() => {
        mesh.material.needsUpdate = true;
        console.log("updated");
    });

It gives this error:

"Uncaught TypeError: m is undefined" [error][1]

Solution

  • After some tweaking, I found that the values of object(or array) in the third argument only supports string types, so passing a object as a value would not work.

    This is the closest workaround that I could think of..

    /* GUI options */
    const guiOptions = {
        mesh_material_map: "color",
    };
    
    /* Textures */
    const textureLoader = new THREE.TextureLoader(loadingManager);
    const colorTexture = textureLoader.load("/textures/door/color.jpg");
    const alphaTexture = textureLoader.load("/textures/door/alpha.jpg");
    const normalTexture = textureLoader.load("/textures/door/normal.jpg");
    
    const guiTextureHash = {
        color: colorTexture,
        alpha: alphaTexture,
        normal: normalTexture,
    };
    
    /* Add to gui */
    gui.add(guiOptions, "mesh_material_map", Object.keys(guiTextureHash)).onChange((value) => {
        mesh.material.map = guiTextureHash[value];
        mesh.needsUpdate = true;
        console.log("updated", value);
    });