Arasto
Arasto

Reputation: 491

Update texture of mesh using ThreeJS & Dat.Gui

I would like the texture of my Mesh to update when clicked on function.

When you click on the 'UpdateMateria' function i'd like the mesh to dispose its current texture and add a new one.

currentLook

Animation Loop

  startAnimationLoop = () => {
   const tableBoard = this.scene.getObjectByName('tableSurface');
   tableBoard.material.map = this.updateMateria;

   this.renderer.render(this.scene, this.camera);
   this.requestID = window.requestAnimationFrame(this.startAnimationLoop);
  };

Dat.Gui

  userGUI = () => {

    const update = {
      updateMateria: function() {
        alert('Changing');
        this.material.dispose();
        this.material.map = texture1();
      }
    }

    this.gui = new dat.GUI();
    const controls = function() {
    this.title = new controls();
    this.gui.add(update, 'updateMateria')
  }
}

When i put the function straight into the 'Animation Loop' this actually updates the texture to the desired one, but the current version gives me 'TypeError: Cannot read property 'dispose' of undefined'

Upvotes: 2

Views: 1014

Answers (1)

Mugen87
Mugen87

Reputation: 31026

First, you can not use the this reference in updateMateria (probably updateMaterial???). Consider to safe the this reference in a variable outside of this function and use this variable instead. Besides, it's not necessary to dispose the material if you just want to change the texture.

userGUI = () => {

    const scope = this;

    const update = {
        updateMateria: function() {
            alert('Changing');
            // scope.material.dispose();
            scope.material.map = texture1();
        }
    }

    this.gui = new dat.GUI();
    const controls = function() {
    this.title = new controls();
    this.gui.add(update, 'updateMateria')

}

three.js R108

Upvotes: 4

Related Questions