Changing the texture of a specific GLTF model in Three.js that is being replicated multiple times

Currently, I am loading a GLTF asset and using it in the scene multiple times.

I am trying to modify the material color of all meshes inside a specific object that is a GLTF model.

traverseMaterials(object, (material) => {
    material.color.set(
        object.info.model.color
    );
});

Although this solution works, it ends up changing the materials of all other GLTF objects as well.

My objective is to only change the specified object and its children's mesh materials colors, not affect all instances of used GLTF models.

I attempted the following approach with no success:

traverseMaterials(object, (material) => {
    let clonedMaterial = material.clone();
    material = clonedMaterial;
    material.color.set(
        object.info.model.color
    );
});

Below is the traverseMaterials function for your reference:

function traverseMaterials (object, callback) {
     object.traverse((node) => {
     if (!node.isMesh) return;
     const materials = Array.isArray(node.material)
     ? node.material
     : [node.material];
     materials.forEach(callback);
  });

}

Answer №1

material = clonedMaterial;

To truly change the reference of node.material, you must explicitly assign the cloned material to node.material.

Answer №2

Big shoutout to @Mugen87 for the helpful suggestion, which led me to modify the traversal in this way:

object.traverse((element) => {
    if (!element.isMesh) return;
    let copiedMaterial = element.material.clone();
    element.material = copiedMaterial;
    element.material.color.set(
       this.state.modelData.statusList[statusIndex].statusColor
    );
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking for a custom JavaScript color wheel with advanced features?

In search of a javascript color picker/wheel that allows users to easily select colors for our paint shop. Once the color is selected, it should automatically add the color value to the shopping cart. Our online store is operated using PrestaShop, so we ...

The fullscreen API allows for the creation of a full-screen element containing internal elements, while also enabling the functionality

Is it possible to utilize the fullscreen API to make any element fullscreen, even if it contains multiple internal elements, while still maintaining the functionality of dropdowns and other custom elements that may be located in different areas of the page ...

Oops! Looks like there was an error. The text strings need to be displayed within a <Text> component in the BottomTabBar. This occurred at line 132 in the

My app includes a bottomTab Navigation feature, but I encountered an error: Error: Text strings must be rendered within a <Text> component. This error is located at: in BottomTabBar (at SceneView.tsx:132) in StaticContainer in StaticCont ...

What could be improved in this AngularJS code snippet?

Currently, I am immersed in an AngularJS book and have extracted the following code snippet directly from its pages: <!DOCTYPE html> <html ng-app='myApp'> <head> <title>Your Shopping Cart</title> </head> & ...

Error encountered in Three.js while attempting to utilize THREE.JSONLoader.parse in place of THREE.JSONLoader.load

After successfully loading a JSON model using THREE.JSONLoader.load, I encountered an issue when trying to create a variable out of it and include data in the main script. This resulted in an exception being thrown by the THREE.JSONLoader.parse call. var ...

"Encountering a Javascript issue while trying to apply a CSS class to a

Encountering issues in Safari desktop / mobile and Internet Explorer. The error message states: In Safari: TypeError: Attempted to assign to readonly property. IE Edge: Assignment to read-only properties is not allowed in strict mode The problem arises ...

What are the reasons for the various methods available for importing my JS code?

Here is the structure of my folders: --public ----frontend.js --views ----fontend.ejs The frontend.js file is located inside the public folder, while the frontend.ejs file is in the views folder. In my HTML / EJS file, I included the JavaScript (fronten ...

The DAT GUI controls are mysteriously absent from the scene

Within a modal, I have set up a threejs scene with three point lights. All functions are exported from a separate file called three.ts to the modal component. The issue I am facing is that when I try to initialize DAT.GUI controls, they end up rendering ...

The constricted styles are causing the whole page to bounce (scroll) up and down

On my SPA frontend, I have a parent div with a height of 580 containing 9 smaller divs (about 190px in height each). The parent div has an overflow set to hidden so that only 3 elements are visible at one time. Every 5 seconds, I change the styles by addin ...

Is your Vue.js chart malfunctioning?

I have been experimenting with chart.js and vue.js. The component I created is called MessageGraph, and it is structured like this (with data extracted from the documentation): <template> <canvas id="myChart" width="400" height="400">< ...

The perfect approach for loading Cordova and Angularjs hybrid app flawlessly using external scripts

We have developed a single page hybrid app using cordova 3.4.0 and angularJS with the help of Hybrid app plugin(CPT2.0) in visual studio 2013. This app contains embedded resources such as jquery, angularjs, bootstrap, and some proprietary code. Additiona ...

Is there a way to determine when the callback function has been called for the final time?

Per the documentation on String.prototype.replace(), if a function is passed to String.replace() with a global regular expression, it will be invoked multiple times. Is there a way to pass a callback within this callback to determine when all invocations ...

the cached token retrieved by adal is consistently empty

To retrieve a cached token, I am utilizing the react-adal api import { authContext, } from '../auth' const AvatarContainer = () => { getPersonPhoto(authContext) return ( <Avatar /> ) } async function getPersonPhoto(au ...

The state in useState is failing to update correctly following selections made within the dropdown menus

I am currently facing an issue with my dropdown disabling function, which is not enabling the dropdown properly. I suspect that this is due to asynchronous problems stemming from the use of useState. const [homeSelect, setHomeSelect] = useState('Home& ...

Adjust the separation between two 3D objects in Three.js to modify their distance

Is it possible to adjust the camera's distance from a stationary 3D object in threejs? I am aware of the "Vector3.distanceTo(Vector3)" function for calculating the distance between two objects, but I haven't found a way to actually cha ...

What techniques can you leverage in React to iterate through nested arrays, such as using .map or other alternatives?

As part of my work, I often come across an Array structure similar to the one below: Array = [ { product1, orderedBy = [{customer1}, {customer2},.....,{customerN}] }, { product2, ...

In order to enhance your programming skills, avoid hard coding functions and ensure that data is returned after binding changes

I am trying to create a method where I can provide a DOM as a parameter and retrieve data from image_preview. The goal is to make image_preview reusable instead of hardcoding it inside the function. Additionally, I want to separate image_preview.model() an ...

Ensure Angular JS includes a space or special character after applying a currency filter

Is there a way to include a space or special character after the "₹" symbol? Desired output: ₹ 49 Current output: ₹49 HTML - {{cart.getTotalPrice() | currency:"₹"}} ...

Express.js Server Side Rendering - GET request for '/json/version/'

I have a running express server that pre-renders my react application. The routes file matches the HomeContainer to the base route / and all other routes match to the page not found. import HomeContainer from 'containers/home-container/home-container ...

Updating the CSS: Using jQuery to modify the display property to none

I am facing an issue with displaying an element that is defined as display:none in CSS. I tried to use the .show() function in jQuery, but it's not working as expected. Here's the code snippet: CSS .element { position: absolute; display: no ...