Saving jsonModel in a class variable in Three.js

I am facing a challenge in storing a loaded JSON model in Three.js using classes. Even though I can add it to the scene, I am unable to use it afterwards. Here is an overview of my code:

class AScene extens THREE.Scene{
 constructor(renderer){
 super();
 this.ground = null;
 this.model = this.createModel(); // It creates and returns a model that encapsulates all models in this scene.
 this.soldier = this.createSoldier(); // I aim to store the loaded object here.
 this.model.add(this.soldier); // This line always results in 'null' or 'undefined'.
 this.add(this.model);
}
 createModel(){ 
  var model = new THREE.OBJECT3D();
  this.ground = new Ground (300, 300, new THREE.MeshPhongMaterial ({map: texture}), 4);
  model.add(this.ground);
  return model; // This part functions as expected.

 }
 createSoldier(){
  var obj = null;
  var loader2 = new THREE.JSONLoader();
  loader2.load('models/untitled.json', function(geometry, materials){
    var material = new THREE.MeshBasicMaterial( { color: 0x0000ff } );
    obj = new THREE.Mesh(geometry, material);
   });
   return obj;
 }
}

Despite numerous attempts, I have been unsuccessful in successfully storing it in the 'this.soldier' class variable. The object loading process itself works well.

Answer №1

The function createSoldier() is not functioning correctly due to the fact that the value of obj is only set in the onLoad() callback of JSONLoader.load(). By the time this callback is executed, the method has already returned a null value.

Your current class structure does not properly handle the asynchronous nature of JavaScript. I recommend gaining a better understanding of Callbacks and Scopes before proceeding with your work. In the meantime, you can implement the following approach:

loader2.load('models/untitled.json',(geometry,materials) => {
    var material = new THREE.MeshBasicMaterial( { color: 0x0000ff } );
    this.soldier = new THREE.Mesh( geometry, material );
});

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

Guide on interpreting unordered lists and returning the outcome to Java

The xhtml-file provided below showcases a structure for content creation: <ui:composition xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" temp ...

Having trouble with the Javascript denial of submit functionality?

I'm dealing with an issue in my code where form submission is not being denied even when the input validation function returns false. I can't figure out what's causing this problem. <script> function validateName(x){ // Validati ...

Class-based Button Transition Effect failing to operate as intended

I want to trigger these 3 events simultaneously when a form is filled out, all initiated by the same button. I have been able to make it work using 3 classes named: "draw dj", which represents the first event "draw1 dj", which signifies the 2nd event "d ...

What is the reason for this code failing to verify the authenticity of the passcode?

The validation process is not functioning properly and there seems to be a missing alert dialog box. I would like the passcode entered by the user to be compared with the constant "Pass". const Pass = '2207' function checkValidity() { con ...

Three-dimensional.js and components of the design

Looking for advice on how to manipulate individual parts of a 3D model in Three.js. My model is made up of various components that I need to control separately. Any tips or suggestions would be greatly appreciated. Thank you! ...

transforming an array into JSON structure using node.js

Hello, I have a list of data that I need to convert into JSON format. Here is an example of how I want the data to look: [ { "slideName": "s0", "imageUrl": "https://s3.amazonaws.com/lifestyle345/testing/slides/cbaa5e650152a0332b494f0074985 ...

Retrieving registered components dynamically in Vue.js

Check out my scenario on jsBin In my setup, I have a selector <component :is="selectedComponent"></component>, along with a <select v-model="currentComponent">...</select> that allows me to choose which one is displayed. Currently ...

Tips for utilizing maps in a react component within a Next.js application

I received an array of data from the backend that I need to display on a React component. home.js import Head from "next/head"; import Header from "../src/components/Header"; import * as React from 'react'; import { styled } ...

The Django Selenium test is encountering a failure due to its inability to locate an element that is added after a click event

I'm currently facing an issue when writing a test for my application as it continues to fail. Despite attempting to use both WebDriverWait and time.sleep(), the problem persists. The troublesome section of the test appears as follows: form_2.find_el ...

Guide to transferring stream input and output between a parent process and a spawned process in Node.js

I am currently attempting to establish communication between two processes using the stdio method: ping.js import { readline } from '../readline'; import { sleep } from '../sleep'; import { spawn } from 'child_process'; con ...

Using NodeJs to Render HTML Templates and Implement Logic on the Server Side

Hello, I am currently working on developing a widget module for my Angular 1 based UI project. This widget is meant to display real-time information. My design involves sending an HTML view to the client from the Node server (potentially using Express.js) ...

A guide to sketching the ellipsoid with three.js

Despite Three.js offering functions for drawing ellipses, I am in need of assistance to draw an ellipsoid instead. Can someone please help me? I have a specific requirement to draw an ellipsoid using three.js. ...

Prevent videos from automatically starting in HTML

I am currently working with Django and I have a requirement to display multiple videos on one page. Is there anyone who knows how to prevent the videos from auto-starting in the iframe? <div class="embed-responsive embed-responsive-16by9"> ...

Setting up JavaScript within a .NET Framework MVC project: A Step-by-Step Guide

Seeking guidance on integrating JavaScript into an MVC project within the .NET framework. Have attempted various tutorials with no luck so far, any help is appreciated. Thank you. ...

Endless Loop Issue with Google Maps API Integration in NextJS-React

Currently struggling to troubleshoot an infinite loop issue in my React function component map. I've spent a considerable amount of time analyzing the code and suspect that it might be related to the useEffects, but I'm unable to resolve it. Atta ...

"Extracting information from a database in Angular Laravel to create a Chart.js display - a step-by-step

Currently, I am working on developing a dashboard application that includes various charts. My aim is to customize the data displayed in each user's chart based on information retrieved from a database. This is how my setup looks like: HTML <div ...

Web Inspector shows no trace of HttpOnly Cookies

My current project involves implementing user authentication for a website using the MERN stack, and I have opted to utilize JWT tokens stored as HttpOnly cookies. Interestingly, when I made the request via Postman, the cookie was sent in the "Set-Cookie" ...

Obtain the properties of a sphere in three.js when it is hovered over with the mouse

In my current project, I am creating a series of spherical objects using three.js by utilizing an array and a for loop. The initial array structure is as follows: atoms = [ ['Na', [0, 0, 0]], ['Na', [0.5, 0.5, 0]], ['Na', ...

Is there a way to begin the Iteration process at 1 by utilizing the Object.entries() method in JavaScript?

const game = { team1: 'Real Madrid', team2: 'Barcelona', players: [ [ 'Courtois', 'Carvajal', 'Ramos', 'Varane', 'Marcelo', 'Casemiro&a ...

Tips on choosing an id value from a JSON dataset and appending it to an array in another JSON object

I am trying to select an object from the JSON data (productData) and add it to another object array (saveProduct) in the JSON data (storeData). Component for productData: import React, { Component } from 'react' import { dragSource, DragSource ...