I have a Three.js Group containing five elements, but I am having trouble accessing the meshes within. Is there a way to properly access the meshes within a Three.js group?

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

I am encountering an issue while trying to access elements within this array. Despite there being a length of 5, the code returns "undefined" and has a length of 0. The image above shows the output of this code.

console.log(scene.children[1].children);

The result of the following code is 0

console.log(scene.children[1].children.length);

The result of the next code snippet is undefined

console.log(scene.children[1].children[0]);

If it helps provide context, here are previous paths:

console.log(scene);

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

console.log(scene.children[1]);

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

As per comments, here is the full code:

import "./styles.css";
... (the rest of the original code goes here)

Answer №1

Your issue stems from asynchronous code causing the loadModels function to load models asynchronously, leading to the rest of the code completing before all calls to this method finish.

To gain a better understanding of why this occurs, watch this informative video on the event loop: https://www.youtube.com/watch?v=8aGhZQkoFbQ.

Loading GLTF models may also introduce some delay based on their size, requiring a few milliseconds before they are accessible within the group.

You can experiment with logging on each tick by modifying your tick method as follows:

const tick = () => {
    // Code snippet for raycaster
    window.requestAnimationFrame(tick);
};

In our threejs experience, it proved beneficial to assign the scene to the global window for convenient access in Chrome. Simply insert the following lines after creating the scene:

window.scene = scene

import "./styles.css";
// Additional imports and setup code...
window.scene = scene;

This modification enables you to access the group via the Chrome console once the GLTF models have loaded. With scene now reachable from devtools, simply type 'scene' to access it or use scene.children[0].children[1] to view your group.

Note: This approach is primarily for debugging purposes.

Answer №2

After much trial and error, I managed to find a workaround for the problem at hand. However, the root cause of the issue still eludes me. Interestingly enough, when I included the

console.log(scene.children[1].children[0]);
within the tick function, the output was puzzling:

undefined
mesh
mesh
mesh

The initial iteration resulted in 'undefined', prompting me to devise a simple solution by checking if it's undefined before proceeding. This adjustment led to an error-free execution and all components working as intended:

// Raycaster logic
raycaster.setFromCamera(mouse, camera);
if (
    typeof scene.children[1].children[0] !== "undefined" &&
    typeof scene.children[1].children[1] !== "undefined" &&
    typeof scene.children[1].children[2] !== "undefined" &&
    typeof scene.children[1].children[3] !== "undefined"
) {
    const intersects = raycaster.intersectObjects([
        scene.children[1].children[0],
        scene.children[1].children[1],
        scene.children[1].children[2],
        scene.children[1].children[3],
    ]);
    if (intersects.length) {
        if (!currentIntersect) {
            console.log("mouse enter");
        }
        currentIntersect = intersects[0];
    } else {
        if (currentIntersect) {
            console.log("mouse leave");
        }
        currentIntersect = null;
    }
}

Yet, the lingering question remains: why does it return undefined during the early iterations?

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

Rearranging Arrays in AngularJS: Ensuring a Specific Element Stays at the

I have exhaustively searched for an answer to my query without success. I hope that my search efforts were sufficient! Here is the issue at hand : <div id="{{expression.comment_id.$id}}" class="comments" ng-repeat="expression in expressions| orderBy:or ...

Show the present category name within breadcrumbs (utilizing angularJS)

Struggling to display category and vendor names on breadcrumbs? Utilizing the ng-breadcrumbs module but encountering difficulties in making curCategory and curVendor globally accessible. Tried various methods without success. Below is the HTML code snippe ...

Tips for developing a dynamic game that adjusts to different screen sizes using Phaser 3

Recently, I've been on the hunt for a way to ensure my game adapts seamlessly to various screen resolutions when using Phaser 3. In the past, I achieved this with ease in Construct 2. However, I'm now curious to explore how best to implement thi ...

Drag and drop a Jquery image onto the div with its top left corner

Drop targets: <div id="targetContainer" style="width:100px; height:100px;> <div id="tar_0-0" class="target" style="position: relative; float:left; width:50px; height:50px; background-color: #fff;"></div> <div id="tar_1-0" class="t ...

I need help with customizing the progress bar in HTML and CSS

How can I create a progress bar like the one shown below: https://i.sstatic.net/BFv87.png .detail-load { height: 42px; border: 1px solid #A2B2C5; padding: 1px; border-radius: 10px; } .detail-load > .detail-loading { ...

React - The previous condition is maintained when selected

A few days back, I encountered a perplexing issue and sought help by posting a question regarding obtaining an index of values. To my relief, I received a reliable answer that enabled me to successfully tweak my existing code. One problem that arose was w ...

Adding a collection to an array in JavaScript

In my dynamic inputs, I am collecting a list of data like the following: FirstNames : Person1 FN, Person2 FN, Person3 FN, ... LastNames : Person1 LN, Person2 LN, Person3 LN, ... To retrieve these values, I use input names as shown below: var Fir ...

Using Jquery to toggle visibility and position of a button when clicked

I'm new to using Jquery and I've been able to create a button that shows a div and moves the button to the right when clicked. I have looked at similar questions about toggling visibility, but I also need to move the button back when it's cl ...

What could be causing my recursive function to skip over certain parts of my JSON data?

UPDATED TO BE MORE CONCISE Hello, I'm looking for assistance with a recursive function that's not returning the expected values from a JSON object. The goal is to retrieve all "Flow" object IDs where the "Type" is either "Standard" or "Block". T ...

How come JSON.parse is altering the data within nested arrays?

In my journey to master Angular 2, I decided to challenge myself by creating a Connect Four game using Angular CLI back when it was still utilizing SystemJS. Now, with the switch to the new Webpack-based CLI, I am encountering a peculiar issue... The fun ...

Having trouble with Vuex in Vue JS when trying to set up a modular store

Currently, I am in the process of building a web application using Vue along with Vuex. Despite being new to Vue, I am attempting to integrate Vuex into my Vue application. However, I am encountering an issue when using modularised Vuex. In my project, th ...

What's the best way to update the value of an angular field upon submission?

Could someone please provide instructions on how to update the myName variable when the "submit" button is pressed? Thank you! app.js: app.controller('SomeController', ['$scope', 'emails', function($scope, emails) { emails ...

AngularJS enables the creation of a checkbox that toggles the visibility of content

As I develop a form, selecting 'Next Section' will reveal a new group of input fields organized into 8 sub-forms. Through checkboxes, I aim to dynamically display the relevant sub-form based on user selections. For example, if there are 5 checkbo ...

jquery activating the toggle function to switch between child elements

I'm facing a challenge where I can't use .children() in this scenario, as it won't work since the elements aren't technically children. Here's the snippet of HTML that I'm working with: <p class="l1">A</p> ...

Using $nin alongside $and in Mongoose

Implementing a filter for an admin user using mongoose operations. The user should be able to view all saved files except for those that are classified as draft files. However, the admin user should still have access to their own saved draft files. Code ...

Attempting to save the result of a fetch call into a variable for the purpose of rendering it as a list in a

I'm attempting to fetch the top 5 NFT collections based on volume and display them in a table format. However, I'm facing an issue where the data is not being mapped correctly and when I click the "get" button, all content on the webpage disappea ...

Challenges with Textures in Three.js

I am encountering some challenges with the texture of my model. Initially, I used a collada model with three.js r50, but now I am attempting to use an .obj model with three.js r56 and I am still seeing black lines on the texture that resemble seams. Can an ...

Personalizing buttons on a carousel in React-bootstrap

I am facing an issue with my carousel and buttons placement. The buttons need to be outside of the carousel, but I'm unsure how to connect them effectively. React-Bootstrap's activeIndex option was suggested, but since my carousel is not cyclic l ...

Using Vue.js to bind labels and radio buttons in a form

My goal is to generate a dynamic list of form polls based on the data. However, using :for or v-bind:for does not result in any HTML markup appearing in the browser, causing the labels to not select the corresponding input when clicked. I have prepared a J ...

Adding an external JavaScript file to an HTML document by importing an array

Having trouble loading an array from an external JS file into my HTML. Snippet from js.js: var temp_max = [4,9,2,5,8,4,2,10]; In the HTML: Note: Be sure to download DateJS and place it in "DATE-JS"!! <!doctype html> <html> ... (HTML c ...