Switch between various 3D models in three.js by utilizing dat.gui interface

I'm currently attempting to switch between multiple 3D models (loaded with OBJMTLLoader.js) that are rendered in my three.js scene. Using dat.gui, I've created a dropdown list of model names where selecting one will add the corresponding obj model to the scene and remove the original one.

In this scenario, I have loaded 2 separate models and added the second one to the scene before setting up the dat.gui controls:

    var loader = new THREE.OBJMTLLoader();

    loader.load("../assets/models/boardlego.obj", "../assets/models/boardlego.mtl", function (obj2) {
        obj2.name = 'lego2';
        });



    loader.load("../assets/models/boardlego2.obj", "../assets/models/boardlego.mtl", function (obj) {
        obj.name = 'lego';
        scene.add(obj);
    });

    camControl = new THREE.OrbitControls(camera, renderer.domElement);

    // call the render function
    render();

    //set up dat.gui controls
    control = new function () {
        this.Templates = 'shortboard';
        }
    addControls(control);
    }

Next, we have the addControls function:

function addControls(controlObject) {
    var gui = new dat.GUI();
    gui.add(controlObject, 'Templates', ['shortboard', 'longboard', 'fish', 'funboard', 'simmons', 'parallel', 'gun']).listen();

Both models are successfully loaded, but only one is added to the scene. Is there a way to add the other model when the 'Templates' control is changed? I attempted to create a separate function called updateboard() and invoked it in the render function, like this:

function updateboard() {
    if(controlObject.Templates === "longboard"){
        scene.add(obj2);
    }
}

Unfortunately, this approach didn't yield the desired outcome. Additionally, I tried implementing an if statement within the render function:

function render() {
    renderer.render(scene, camera);
    if (scene.getObjectByName('lego')) {
        scene.getObjectByName('lego').scale.set(control.Length, control.Thickness, control.Width);  
    }

    if(control.Templates === "longboard"){
        scene.add(obj2);
        }

However, this method also proved unsuccessful. Any assistance or guidance would be highly appreciated! Alternatively, if you can point me towards a relevant example, that would be wonderful too! Thank you in advance.

Answer №1

Populate your objects in an array.

 let myModels = [];
 let loader = new THREE.OBJMTLLoader();

     loader.load("../assets/models/boardlego.obj", "../assets/models/boardlego.mtl", function (obj2) {
      obj.name = 'lego2';
     myModels.push(obj);
    });

    scene.add(myModels[0]); // 0 represents the first model, 1 would be the second

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

Exploring Angular 1.5: A guide to binding a transcluded template to a component's scope

Currently, I am utilizing a form component that includes common validation and saving functions. Inputs are injected into the form as transcluded templates in the following manner: <form-editor entity="vm.entity"> <input ng-model="vm.dirt ...

Verifying a user's name when navigating a route

Hey everyone, I've been working on this project for the past 3 hours and could really use some help. I created an express webapp with an admin page. The register and login functionalities are all set up using passport. I have a function to check if th ...

Res.redirect does not seem to be functioning properly while working with React

In my project, I am using React for the frontend and have created an API using Express. I have implemented code to store a JWT token in the cookies during the initial login. However, when attempting to log in again, the code is supposed to check if a token ...

Problem with BehaviorSubject: next() method is not functioning as expected

My goal is to utilize an angular service for storing and communicating data via observables. Below is the implementation of my service: public _currentLegal = new BehaviorSubject({ name: 'init', _id: 'init', country: 'init& ...

Getting specific information from a cell in a table within an AngularJS application

I need to extract the data "Crab" from this table: Sushi Roll FishType Taste Level Cali Roll Crab 2 Philly Tuna 4 Rainbow Variety 6 Tiger Eel 7 Here is the code snippet that currently re ...

Show the value of a JavaScript object in VueJS

New to Vue and need some guidance... I'm having trouble accessing the values in a JS object displayed in the DevTools within one of my routes in a Vue app. Specifically, how can I display the values from filteredData:Array[1]? https://i.sstatic.net/ ...

Inject the ng-repeat variable into a personalized directive

When working with an ng-repeat and a custom directive, I am facing the challenge of passing the "item" variable from ng-repeat to the directive. Here is an example code snippet illustrating this situation: <li ng-repeat="item in list"> <div c ...

Increase the size of the grid system column upon clicking on a Bootstrap icon

I am using Google Maps in a tab with Bootstrap, but the map is too small. I would like to change the Bootstrap grid system when I click on a FontAwesome icon: the first column should turn into col-md-8, and the second column should become col-md-4. Here i ...

Can a string be transformed into HTTP POST parameters?

Below is a snippet of code where I've utilized the .serialize() method to convert all form inputs into a string, which is then sent to the server: $.ajax({ type: "post", url: wp_urls.ajax_url, data: { action: "submit_form", ...

What is the best way to turn off jQuery UI (widget) for a particular element?

Is it possible to disable the Jquery-UI selectmenu widget for a specific element in my project so that it reverts back to its native look and functionality? I have tried various solutions suggested in a Stack Overflow thread about disabling theming for a ...

Ban on the utilization of emojireact-role in external channels

How can I ensure that the bell reaction only gives a role in a specific channel? The provided code is below. Additionally, is there a way to restrict this feature so only administrators can assign roles through reacting with a bell emoji? Any assistance ...

How can you iterate over the input elements that are currently visible within a form using Javascript?

Is there a way to clear the values of all visible input fields in a form using JavaScript? I'm currently struggling with setting text inputs to empty as they come out as undefined. Any suggestions on how to achieve this? ...

JavaScript error: Cannot read property 'str' of undefined

I'm attempting to retrieve specific values from a JSON array object, but I encounter an error message. var i = 0; while (i < n) { $.get("counter.html").done(function (data2) { var $html = $("<div>").html(data2); var str = ...

Images cannot be uploaded using ajax

I have been troubleshooting an issue with uploading image files using ajax without refreshing the page. However, I am facing a problem where the file does not get moved to the specified folder even after implementing basic PHP code for file upload. if($_S ...

Issues with the functionality of the node.js socket.io listener

I am currently experiencing an issue with private messaging in my chat application. The private message functionality does not seem to be working as expected. Below is the code snippet from the app.js file: var express = require('express'),htt ...

Transitioning from the Play mode to the Pause mode upon pressing the Set button

Is there a way to make the button switch from play to pause once the 'Set' button is clicked? Clicking on 'Set' should change the SVG to display the pause button icon. Snippet of Code: https://jsfiddle.net/192h0w85/195/ (function ...

Iterate through each field with getElementsByName to retrieve values triggering the onChange event

I am working on a contact form that includes inputs, selectors and radio buttons. Doubt 1: I am trying to figure out how to retrieve the index of a field using the getElementsByName method with the onChange event. Would a For Loop be the appropriate solut ...

Exiting a Node.js process using process.exit() may not result in a clean exit, especially when dealing with asynchronous file writing

tl;dr: When using asynchronous fs.writeFile in Node.js from asynchronous events or loops and then calling process.exit(), the files are successfully opened but the data fails to be flushed into the files. It appears that the callbacks given to writeFile d ...

UnhandledPromiseRejectionWarning when chaining functions in Node Express is a common issue that needs attention

Currently, I am refactoring a Node Endpoint to handle two tasks: Verify if the user exists Add the user to the database controller.js exports.signup = (req, res) => { methods.checkUser('email', req.body.email) .then(methods.addUser(r ...

Displaying content in Bootstrap 5 modal with jQuery may cause a delay in the appearance of a centered spinner before the content loads

In my Bootstrap 5 modal, I have implemented specific functionality in jQuery where a centered spinner is supposed to show up in the modal before loading the content. You can see a live example of this here. The issue I am facing is that the spinner takes ...