What steps can be taken to avoid the destruction of an object following its use of the .load() function in JavaScript (specifically in three.js)?

I'm facing an issue with preventing the destruction of my object after loading it.

var loader = new THREE.ColladaLoader();
var rescue;
loader.load(
    'Improved_Person_Maker_better_quality.dae',
    function(collada) {
        scene.add(collada.scene);
        collada.scene.position.set(-25, 1, 25);
        collada.scene.rotation.x = -Math.PI / 2;
        rescue = collada.scene;
    },
    function(xhr) {
        console.log((xhr.loaded / xhr.total * 100) + '% loaded');
    }
);

rescue.position.set(-20, 1, 25);

Unfortunately, the last statement is not feasible as the loaded mesh no longer exists. Is there any way to rescue collada.scene?

Answer №1

The loading process is performed asynchronously.

This indicates that rescue.position.set() is invoked before rescue is actually defined in the loader callback.

To resolve this issue, simply set the position within the callback function, as you have already done.

If you need to reference rescue later in your code, you can follow this approach

if (rescue !== undefined) {
    // your code here
}

Working with three.js version r.75

Answer №2

Give this a shot:

let saving; 
let handler = new THREE.LoadingManager();
handler.onProgress = function(item, progress, total) {
    console.log(item, progress, total);
};
handler.onLoad = function(){
       saving.position.set(-20, 1, 25);
};
let loader = new THREE.ColladaLoader(handler);
loader.options.convertUpAxis = true;

loader.load("<url path for the file>", function(collada) {
       scene.add(collada.scene);
       collada.scene.position.set(-25, 1, 25);
       collada.scene.rotation.x = -Math.PI / 2;
       saving = collada.scene;
    }, function(xhr) {
        console.log((xhr.loaded / xhr.total * 100) + '% loaded');
});
}

The Loading Manager allows for flexible asynchronous loading management, enabling you to handle multiple files at a later stage.

Answer №3

I want to extend a huge thank you to Stallion and Westlangley for guiding me in the right direction with asynchronous loading.

Although I came across a solution here, I feel it is necessary to reproduce it for others to benefit.

The key to resolving the issue lies in creating a standard THREE.Object3d() object and being able to include each object as a child of another. Following this approach, I executed the following steps:

loadObject: function(){
    var loader = new THREE.ColladaLoader();
    var container = new THREE.Object3D();
     loader.load(
'Improved_Person_Maker_better_quality.dae',
function ( collada ) {
    container.add(collada.scene);
},
function ( xhr ) {
    console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );

});
    return container;
}

For the sake of flexibility, I decided to create a new function for this purpose.

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

Dividing a string yields varying outcomes when stored in a variable compared to when it is displayed using console.log()

When the `$location` changes, a simple function is executed as shown below. The issue arises when the assignment of `$location.path().split("/")` returns `["browser"]` for `$location.path() == "/browser"`, but when run directly inside the `console.log`, ...

What is the best way to describe duplicate keys within a JSON array?

I have created a specialized program to extract Dungeons and Dragons data from JSON files. While the main functionality is complete, I am struggling with defining unique keys for multiple attack options without manually assigning individual identifiers. H ...

Concealing the rear navigation button within the material carousel

I have a material css carousel, and I am trying to hide the back button on the first slide. I attempted to use the code below from a previous post The following code snippet prevents the user from looping through the carousel indefinitely. Stop looping i ...

What is the best way to include message body in CDATA using strophe?

I have a task to create messages in a specific format by using the following code: $msg({to: 'user', from: 'me', type: 'chat'}).c("body").t('some data'); This code generates the message structure as follows: <m ...

Guide to importing JavaScript in an npm package using TypeScript and JavaScript

I recently downloaded a library that includes both Typescript and its corresponding javascript version. Despite trying to declare import Library from "@scope/library", my application is only able to access the Typescript version, even after adding the .js ...

Using JavaScript to dynamically insert HTML content and create a toggle effect

Within a div, I have a collection of large images that I am attempting to insert into another div using JavaScript toggle functionality. Please test the code snippet provided below. $(".toggleimages").on("click", function(e) { e.preventDefault(); ...

Automatically update the div every few seconds and pause when it has loaded successfully

I am facing a challenge in creating a div that refreshes automatically every 10 seconds, but stops when it successfully loads. Here is the jQuery script I have developed: <script type="text/javascript"> $(document).ready(function(){ var j = jQuer ...

What are the steps to integrate mailjet into my Vue application?

I am looking to utilize mailjet for my contact form. I have installed it using "$ yarn add node-mailjet" and followed the steps provided. However, I am a bit confused about whether I am integrating mailjet correctly. Below is the code I am currently using: ...

Modify content or display picture within accordion panel based on its identifier

In my view, I have a model representing a list of items. Each item has a unique ID, which is included in the H2 header tag. The details of each item are displayed in a div below the header. Initially, there is an image within the header that is set to disp ...

Create a series of vertical lines using jQuery

I'm dealing with a JSON data set that I want to use to generate a grid. In addition to the grid, I also need to display vertical lines above it based on certain values: var arr = []; arr= [ {"Measure":"Air Pollution","Rank":"1","Value":"15.5"}, ...

Menu icon in Next.js/React/Tailwind not triggering close action when clicked again, causing responsiveness issue

Hey there, I'm relatively new to working with Next.js and React. Right now, I'm tackling the challenge of creating a responsive navbar that toggles open and closed when clicking on the hamburger icon (and should also close when clicked outside th ...

Transform a Django/Python dictionary into a JavaScript dictionary using JSON

I need to convert a Python dictionary into a JavaScript dictionary. From what I understand, I have to first convert the Python dict into JSON format and then transform it into a JavaScript Object. view.py jsonheaderdict = json.dumps(headerdict) {{jsonhe ...

Iterate through the object received from the node promise and pass it to the subsequent .then method

After grappling with this issue for what feels like an eternity, I find myself immersed in learning about Node.js and trying to grasp the concept of promises. My current challenge involves retrieving data from the Spotify API, starting with fetching my ow ...

Creating and deploying a basic Angular2 application in cordova

I have a pre-existing app developed in Angular2, which is quite basic. Upon attempting to build it for Android using Cordova, the debug build successfully installs on the system but gets stuck at the loading stage. I am seeking guidance on how to ensure th ...

How can I use a JavaScript function to remove an element from a PHP array?

Imagine I have a PHP session array: $_SESSION[MyItems]=Array('A'=>"Apple", 'B'=>"Brownie", 'C'="Coin")) which is utilized to showcase items on a user's visited page. I want the user to have the ability to remove o ...

I have been working on incorporating a menu item in React, but I keep encountering an error

I am using the MenuItem component to create a dropdown menu in my React project. Despite importing the necessary package, I am encountering an error when running the server. I have searched for solutions but haven't found a definitive me ...

Steps for storing div content (image) on server

Currently in the process of developing a web application that allows users to crop images. The goal is for users to have the ability to email the URL so others can view the cropped image, ensuring that the URL remains active indefinitely by storing every c ...

Transforming a jQuery menu into an active selection with Vue JS

I am looking to transition away from using jQuery and instead utilize Vue for the front end of a menu. Specifically, I need to add an active class and a 'menu-open' state to the appropriate nested list items, similar to what is achieved in the pr ...

Utilizing HTML data retrieved from an ajax request

I am utilizing a load more button to display content fetched from a database via ajax. Here is how the ajax call is structured: // JavaScript Document // Function to load more builds $(document).ready(function(){ var pageIndex = 1; $('#loadmorebuild ...

Adding AngularJS data to JSON file for update

I'm feeling lost on where to begin with this. I am working with an AngularJS form and I need it to add the data it sends to a json file. I understand that AngularJS is client-side, so my main issue lies in figuring out how to manage the data being sen ...