What is the best way to load a model and save it to a variable for future use?

One issue I'm facing involves loading a model in this manner:

var Beech;
var loader = new THREE.JSONLoader();
loader.load( "./models/trees/Beech/Beech.json", function( geometry, materials ) {
Beech = addMorphTree(geometry,materials,0.5); });

and utilizing it like so :

function addMorphTree(geometry,material,scale){
            mat=new THREE.MeshFaceMaterial( material );
            mat.side=THREE.DoubleSide;
            Tree = new THREE.Mesh( geometry,mat);
            Tree.scale.set(scale,scale,scale);
            //Tree.position.set(x,y,z);
            Tree.rotation.x = Math.PI/2;

            //scene.add( Tree );
        return Tree;}

I am wondering how I can use the 'Beech' variable to create duplicates of the model without having to load it repeatedly. When attempting to use

scene.add(Beech);

outside the loader, the model fails to appear. I've come across similar queries, but the solutions involve adding the model to the scene inside the loader.

Answer №1

It seems that the model doesn't appear in the scene when attempting to add it outside of the loader because the loading process is asynchronous. This means that while the loader is loading, the rest of the code continues execution. Therefore, trying to add "Beech" to the scene right after the loading function would result in it not being fully loaded yet.

var Beech;
var loader = new THREE.JSONLoader();
loader.load( "./models/trees/Beech/Beech.json", function( geometry, materials ) {
Beech = addMorphTree(geometry, materials, 0.5); });
scene.add(Beech);  // <-- this line will execute before the function above is completed,
                   // causing an undefined variable to be added to the scene.

If you need multiple instances of the variable, you could consider using the clone() function. Since Beech is a Mesh object and Mesh inherits from Object3D, it can also make use of Object3D member functions.

var Beech;
var loader = new THREE.JSONLoader();
loader.load( "./models/trees/Beech/Beech.json", function( geometry, materials ) {
Beech = addMorphTree(geometry, materials, 0.5); 
for(var i=0; i<5; i++){
  scene.add(Beech.clone()) //creates 5 trees
}
});

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

Retrieve information from an SQL database using user input in a Classic ASP form without the need to refresh the page

Currently, I am in the process of incorporating a new function into an existing Classic ASP system. This feature involves allowing users to scan a barcode that will automatically populate a text field within a form inside a bootstrap modal. The scanner has ...

The error message "Evaluating this.props.navigation: undefined is not an object" indicates that there

In the navigation bar, I am trying to keep a touchable opacity at the top right. When this touchable opacity is pressed, I want to redirect the user to the home page. constructor(props) { super(props); this.state = { stAccntList: [], ...

Unleashing the power of plugins and custom configurations in your next.js next.config.js

const optimizeNext = require('next-compose-plugins'); const imageOptimization = require('next-optimized-images'); const config = { target: 'serverless', }; module.exports = optimizeNext([imageOptimization], config); tra ...

A guide on how to assign a placeholder as the default value for a date picker

Currently using Vue3 with options API, and this question does not pertain to date formatting. Looking at the code provided on StackBlitz here, the default format for the date being initially set is dd.mm.yyyy. I am interested in knowing how to set the date ...

Ways to usually connect forms in angular

I created a template form based on various guides, but they are not working as expected. I have defined two models: export class User { constructor(public userId?: UserId, public firstName?: String, public lastName?: String, ...

Enhance a React component by including additional properties when passing it into another component through props

I have a parent element with a dynamically changing height that I need to pass down to its child elements. To get and set the height of the parent element, I am utilizing a ref. The challenge lies in passing this height value from the parent component to ...

In React js, what is the best way to retrieve the first unique ID element as well as the last unique ID element from an

Hey there, I'm working with some data and you can find the link to it here: https://stackblitz.com/edit/react-26pgys. My goal is to filter the JSON and extract the first unique ID along with the last unique ID. I've already made an attempt at fi ...

Regular expression that can be used to extract information from a text file by filtering and returning only

When I open a text file, it contains several lines like the examples below. surname australia enter name j.jonhs enter name j.cause enter name f.london enter I am seeking assistance to modify the code snippet below so that it captures the first line m ...

Is it possible to trigger an action in Vue Store using a Window/onunload event?

Currently, I am working on integrating an event listener for the `unload` event to trigger a Vuex store action that will help identify the ID of the closing window. This is crucial in our application where we need to manage the number of open tabs due to r ...

Modifying button appearance based on state change in AngularJS

I have a button with a grey color and I want to create two different states for it: one that is selected (blue) and another that is in an idle state (grey). Currently, I am working on Angularjs but I am fairly new to this platform. Could you kindly provid ...

AngularJS promises are known for returning the object itself instead of just the resolved value

function getBusTimetable() { var waiting = $q.defer(); var busData = $http.get('https://bus.data.je/latest'); busData.success(function(response) { waiting.resolve(response); }); busData.error(function(error) { waiting.reject( ...

Steps for adding an HTML string to a div element using Ajax

I am facing some major challenges with Ajax, especially when it comes to appending HTML code to a div. I am attempting to append this HTML string to <div id="content-loader"></div> PHP function getLogo(){ $logo = '<div class="bg- ...

Ways to automatically scroll text inside a div based on the div's width

I currently have a div with a fixed width. My goal is to automatically scroll the text (left and right in a horizontal direction) within the div if the content exceeds the width of the div. How can I achieve this using CSS or jQuery? The class for the div ...

Create a custom shader material to display a video with THREE

As I embark on loading a video onto an animated WebGL plane with a custom shader material, my approach involves using a pre-loaded video to draw an image onto a canvas and then passing it to my shader uniforms in the render loop: // Render loop useFrame(( ...

What is the reason behind the error "Uncaught SyntaxError: Malformed arrow function parameter list" when using "true && () => {}"?

When the code below is executed: true && () => {} it results in an error message stating: Uncaught SyntaxError: Malformed arrow function parameter list Why does this happen ? Update: I am aware that wrapping the function in parentheses reso ...

Creating a React functional component that updates state when a specific window breakpoint is reached

Having an issue with my code when it hits the 960px breakpoint. Instead of triggering once, it's firing multiple times causing unexpected behavior. Can someone help me troubleshoot this problem? const mediaQuery = '(max-width: 960px)'; con ...

"Utilize parameter passing with mapGetters in the Vuex state management system

Hello there! I'm currently working on a Vue.js project and using modules. I am trying to get filtered data from a getter, but I'm unsure how to provide parameters. Specifically, I need to pass a 'name' parameter to the Getter. How can ...

Creating a dropdown menu utilizing JavaScript/jQuery arrays

Looking to create an HTML select menu using a JavaScript array where the keys are used as values for options. The challenge is when entering numbers as keys, they should be accepted in the code. a([selected="No of rooms", 1="1", 2="2", 3="3", 4="4", 5="5" ...

Turn off the scrollbar without losing the ability to scroll

Struggling with disabling the HTML scrollbar while keeping the scrolling ability and preserving the scrollbar of a text area. Check out my code here I attempted to use this CSS: html {overflow:hidden;} Although it partially worked, I'm not complete ...

Generate an asynchronous boolean promise when calling the isPresent function in Protractor

I'm currently working on a function that checks the presence of an element and returns a boolean value accordingly. However, I am facing an issue where the response includes unnecessary information. the output displays: false How can I adjust my cod ...