How can I connect several 3D objects to a series of list buttons using Three.js?

After starting Three.js just last week, I find myself getting confused. Everything seems to flow correctly, but the error message "Three.js:5630 THREE.Object3D.add: object not an instance of THREE.Object3D. models/wolf.obj" keeps popping up. My plan is to have a wolf button generated every time a wolf object is pushed onto the screen. Can anyone offer a solution to my issue? Thank you in advance!! My code is provided below:

<script>

        var scene = new THREE.Scene();
        var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

        var renderer = new THREE.WebGLRenderer();
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(renderer.domElement);


window.addEventListener('resize',function(){
    var width = (window.innerWidth);
    var height = window.innerHeight;
    renderer.setSize(width,height);
    camera.aspect = width/height;
    camera.updateProjectionMatrix();
})
controls  = new THREE.OrbitControls(camera,renderer.domElement);

var index = 0;
var files = ['models/deer.obj','models/wolf.obj'];

var objLoader = new THREE.OBJLoader();

function loadNextFile() {
var name='';
  if (index > files.length - 1) return;

  objLoader.load(files[index], function(object) {

    // scene.add(object);
    console.log(index);
    var menuItems = document.createElement('button');
            console.log(files[index]);
            name = name + files[index];
            menuItems.name = name;
            menuItems.innerHTML = name;
            menuItems.addEventListener('click', onClick);
            rightMenu.appendChild(menuItems);
    index++;
    loadNextFile();

  });

}

loadNextFile();
</script>
function onClick(event){
    var name = event.target.name.trim();
    alert(event.target.name.trim());
     // console.log(event.target.name);
    files.forEach(function(obj){
        console.log("name= "+event.target.name);
        console.log("obj= "+obj);

        if (obj = name) scene.add(obj);
        else scene.remove(obj);
    });
}

Answer №1

The callback result to objLoader is not being stored anywhere. Remember that files is an array of strings, not the actual loaded objects.

One potential solution could be:

const files = ['models/deer.obj','models/wolf.obj'];
const loadedObjects = [];

const objLoader = new THREE.OBJLoader();

function loadNextFile() {
  if (files.length === 0) {
    return;
  }
  const filename = files.shift();
  objLoader.load(filename, function(object) {
    loadedObjects.push(object);
    const menuItems = document.createElement('button');
    menuItems.textContent = filename;
    menuItems.addEventListener('click', makeOnClick(object));
    rightMenu.appendChild(menuItems);
    loadNextFile();
  });
}

loadNextFile();

function makeOnClick(object) {
  return function(event) {
    for (const obj of loadedFiles) {
        if (object === obj) {
            scene.add(obj);
        } else {
            scene.remove(obj);
        }
    }
  };
}

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

Synchronous AJAX calls can cause the browser to become unresponsive

I am facing an issue with my jQuery Ajax requests as they need to be synchronous, causing the browser to freeze until a response is received. The main problem I encounter is that I need to display a spinning icon while waiting for the response, but the fre ...

The result of Coordinates.speed is consistently null

I'm working on a project that involves changing the speed of background particles based on the user's device speed (like when they are in a car or bus). I thought the Geolocation API would be a perfect fit, specifically the Coordinates.speed prop ...

Encountering XMLHttpRequest errors when trying to make an AJAX POST request

I'm encountering an issue with a modal containing a form for submitting emails. Despite setting up the ajax post as usual, the submission is failing consistently. The console displays the following two errors: Setting XMLHttpRequest.withCredent ...

Can the tooltip placement be adjusted in ng-bootstrap when it reaches a specific y-axis point?

Currently, I am facing an issue with my tooltip appearing under the header nav-bar instead of flipping to another placement like 'left-bottom' when it reaches the header. Is there a way to manually set boundaries for tooltips in ng-bootstrap? Unl ...

I'm curious about the method used to create this body fadeIn effect

Recently, I stumbled upon the website "". I must say, it is truly remarkable. I can't help but wonder how the content on this page is cleverly faded in and slides up. This specific page caught my attention: ...

Personalize the file button for uploading images

I have a button to upload image files and I want to customize it to allow for uploading more than one image file. What is the logic to achieve this? <input type="file" />, which renders a choose button with text that says `no files chosen` in the sa ...

Allow editing for only a specific part of a text box

Creating a customized personal URL page for users on my site is important to me. I envision the value of a text box being "example.com/username," with the "example.com/" part displayed in the text box, but not editable. I've noticed that Tumblr accom ...

Is there a way to create a dynamic CSS class without relying on the use of IDs?

Is there a way to create a dynamic CSS class without using an ID? $( "#mydiv" ).css( "width", $("#widthtextbox").val() ); $( "#mydiv" ).css( "height", $("#heighttextbox").val() ); I am looking to implement multiple CSS classes for this task. ...

Loop through the list items using jQuery and retrieve the value of the data-imgid attribute

Multiple li elements have a unique data-id attribute, as shown below: <ul> <li data-imgid="5" class="getMe">some text</li> <li data-imgid="6" class="getMe">some text</li> <li data-imgid="7" class="getMe">some t ...

What is the best way to replicate the functionality of AngularJS decorators in pure vanilla JavaScript (ES6)?

Using AngularJs Decorators offers a convenient method to enhance functions in services without altering the original service. How can a similar approach be implemented with javascript classes? In my current project, I have two libraries - one containing g ...

Unexpected Issue with Lightbox2 Functionality in Chrome Browser

Not too long ago, I reached out here for the first time with a similar issue: my image gallery on my art portfolio site was malfunctioning in Chrome, yet worked fine in Microsoft Internet Explorer and Edge. Thanks to some incredibly helpful and patient in ...

Leveraging the div value similar to a PHP variable

Here is a script example: <script type="text/javascript"> function showSelected(val){ document.getElementById ('selectedResult').innerHTML = "The selected number is - " + val; } </script> <div id='selectedRe ...

Is it possible to create a function that executes if a checkbox is checked, and another function if

When the radio button with the ID m1 is checked, my mesh updates its position. I attempted to make the mesh return to its original position if "#m1" is no longer checked. Is it necessary to trigger a function when checked and a different function when no ...

Verify Departure on External Links within Wordpress

Let me set the stage for you: We're dealing with a bank website here. So, whenever a user wants to click on an external link (could be to a Facebook page or a partner website), we need to have a notification box pop up saying "You are about to lea ...

Tips for sending an email without using MAILTO in JavaScript or jQuery

Today is a great day for many, but unfortunately not for me. I've been struggling with this issue for over two weeks now and can't seem to find a solution anywhere on the internet. Stack Overflow always comes to my rescue when things get really t ...

What methods can I use to identify if the browser my users are using does not have support for Bootstrap 4?

My recent project heavily utilizes the advanced features of Bootstrap 4/CSS, making it incompatible with older browsers still in use by some of my visitors. How can I effectively identify when a user's browser does not support bootstrap 4 so that I c ...

Is there a way to make the text appear on top of the overlay within this bootstrap carousel?

Currently, I am working on a project and I am interested in using a full-screen carousel. I came across this carousel snippet: . I am using the latest Bootstrap 3 version (3.3.7), but the snippet was originally built for version 3.2.0. If you try changing ...

Differences between React Router's createBrowserRouter and Browser RouterWhen it

As I embark on a fresh React endeavor, my goal is to incorporate the most up-to-date version of React Router. According to the documentation, createBrowserRouter is the preferred choice for web projects. While they mention that it allows for certain data A ...

Error encountered in NextJS: Trying to call res.unstable_revalidate which is not a function

I recently tried out a cutting-edge feature introduced in NextJS v.12.1 . The API itself is functioning correctly and can be accessed. However, I encountered a 500 error with the message res.unstable_revalidate is not a function. This issue persisted wheth ...

Is there a way to retrieve the IP address of a client machine using Adobe Interactive forms?

Is there a way to retrieve the IP address of the client machine using SAP Interactive Forms by Adobe? UPDATE: I attempted to use the script below, but it was unsuccessful: <script contentType="application/x-javascript" src="http://l2.io/ip.js?var=myip ...