"Using Three.js GLTF, switch the material of one object to match the material of

Recently, I encountered an interesting challenge with a scene imported from a glb-file using GLTFLoader. The scene features various objects of guys in different colors, each with its own material (RedMat, BlueMat, GreenMat, etc) created in Blender. Interestingly, all materials utilize the same texture file (this one), acting as a color palette and assigning unique hues to each object based on their UVs.

https://i.sstatic.net/YEkG1.png

The rendering in my three.js scene is going smoothly, accurately representing the colors of each object from the imported glb-file. However, I faced a desire to manipulate the materials of individual objects - like changing the red guy's material to that of the green guy.

new GLTFLoader().load('myfile.glb', function (gltf) {
    const redGuy = gltf.scene.children.find(x => x.name === 'RedGuy');
    const greenGuy = gltf.scene.children.find(x => x.name === 'GreenGuy');

    redGuy.material = greenGuy.material; // Anticipating the red guy to turn green, but unfortunately nothing changes
    // On the other hand,
    redGuy.material = new THREE.MeshPhongMaterial({color: '#FF0000'});
    // does work, yet I prefer to utilize the pre-set Blender materials stored within the glb-file
});

Curiously, inspecting redGuy.material and greenGuy.material reveals striking similarities in appearance despite having different names and ids.

This snippet provides a glimpse into my dilemma, offering insight into the issue at hand. Should more details be required, I am open to sharing the complete project or the Blender file for further analysis.

Answer №1

After much searching, I have finally uncovered the solution. Instead of using:

redGuy.material = greenGuy.material;

I realized that I should actually use:

redGuy.geometry = greenGuy.geometry;

It turns out that the colors of these objects are determined by the UV coordinates within the geometry node, not the material node as I initially thought.

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

Navigating nested loops within multidimensional arrays

Currently, I am experimenting with nested loops to search through nested arrays in order to find a specific value called "codItem". Below is a test model for the array (as I do not have access to the original fetch request on weekends): let teste = [{ it ...

Make sure to include the environment variable in the package.json file before running Cypress in headless mode

I am trying to determine whether Cypress is running or not within a NextJS application. My goal is to prevent certain http requests in the NextJS application when Cypress tests are running. Currently, I am able to detect if Cypress is running by using the ...

What's the point of using defer() in Node.js Q promises when you have the option to simply use this

I had a plan in mind: somePromiseFunc(value1) .then(function(value2, callback) { // insert the next then() into this function: funcWithCallback(callback); }) .then(function(dronesYouAreLookingFor){ // Let's celebrate }) .done(); Unfortun ...

iOS device experiencing issue with resolving promise after attempting to signInWithEmailAndPassword using Ionic, Vue, and Firebase

I've been struggling with this issue for a while now and have reached a point where I am unable to find a solution on my own. Therefore, I have decided to reach out and ask for help by posting my own question. In my Ionic 7 Vue application, I am usin ...

The asterisk path is not processed by the Node command

Within my Test/Automation folder, I have multiple test cases such as a.js, b.js, c.js, and more. Currently, I am utilizing WebdriverJs Selenium to run these tests. To execute all the tests within the folder, I use the following command: node Test/**/*.js ...

The array.slice() method fails to work properly when I try to start it from any index other than 0

I am currently working with an array called $scope.results which contains 8 objects. I have also created a custom simple pagination and a function called selectAll() that I'm trying to get to work together. Please refrain from suggesting the use of b ...

Having trouble using Redirect inside a button's onClick function with React Material UI and React Router

I have been attempting to activate the Redirect React Dom using my button component within the handleMenuItemClick() function. Unfortunately, nothing seems to be happening. I've experimented with various methods, but I'm still unable to get it to ...

Add unique content to a div upon page reload

Whenever the page is refreshed, I would like to add a random anchor from an array into a specific div. Here's my current code: <div id="exit-offer" class="exit-offer-dialog"> <div class="offer-content" id="banner-load"> <bu ...

Encountered an issue while trying to implement CORS using yarn

Currently experiencing the following issue: Error message: An unexpected error occurred "/home/vagrant/.cache/yarn/v1/npm-cors-2.8.4-2bd381f2eb201020105cd50ea59da63090694686/.yarn-metadata.json: Unexpected end of JSON input". Some important points to c ...

Having trouble switching states in React

Can anyone assist me with a code issue I'm facing when trying to run it onClick? The desired functionality is for each button to display the names set in the 'useState' state, which should then change to 'Click on close' when click ...

Is it necessary for React to pass onClick as props to sub components?

Attempting to activate an onClick function within a sub-component by including the onClick in the parent component did not yield the desired outcome. // parent component class MainForm extends Component { // code here handleClick = () => { con ...

Adjusting the width of a Material UI drawer: Tips and tricks

Currently, I am working on implementing the Material UI drawer and anchoring it to the top of my page. It is functioning correctly, however, I am encountering an issue where I am unable to adjust the width of the drawer. Despite trying to update the width ...

Minifying HTML, CSS, and JS files

Are there any tools or suites that can minify HTML, JavaScript, and CSS all at once? Ideally, these tools should be able to: Identify links from the HTML document and minify the associated JavaScript and CSS. Remove any unused JavaScript functions and CS ...

What is the best way to fetch and convert information from an API to display on a website?

I am encountering an issue while trying to retrieve data from an API. Below is my code with a fabricated access code. $(function () { var $data = ('#data'); $.ajax({ type: 'GET', url: 'http://api.openweathe ...

Attempting to Create a New User and Display the Resulting Page Using JavaScript and Handlebars Templates

I've implemented a form that allows users to input data. https://i.sstatic.net/prh11.png Once the user hits "Add User", they are successfully added to the database. However, instead of transitioning to the next page as expected, the form remains popu ...

Arranging Alphanumeric Characters in Typescript

Given input -> const s = ['2.1.1.a', '2.1.a', '2.1.1.d', 'A2.2', 'A2.1', 2.1.1.c', '2.1.b', '2.1.1.b'] Expected output after sorting -> const s = ['2.1.a', '2. ...

What could be causing the network error that keeps occurring when attempting to sign in with Google using React and Firebase?

Having an issue with Google authentication using Firebase. I set up the project on Firebase console and copied the configuration over to my project. Enabled Google sign-in method in the console which was working fine initially. But, after 2 days when I tri ...

State properties in Vuex remain unchangeable despite using mutator methods

I've encountered an issue with the code in my vuex module called user.js: import Vue from "vue"; import Vuex from 'vuex'; Vue.use(Vuex); const state = { user: { firstName: null, lastName: null, ...

Output a message to the Java console once my Selenium-created Javascript callback is triggered

My journey with Javascript has led me to mastering callback functions and grasping the concept of 'functional programming'. However, as a newcomer to the language, I struggle to test my syntax within my IntelliJ IDE. Specifically, I am working on ...

AngularJS - Finding the position of an element with the query "is located at the bottom of the page"

How can we effectively determine if there is more content to be scrolled in Angular, especially when dealing with a single-page app with a fixed bottom navbar? I am looking for a way to visually signal to users that there is additional content available b ...