Fetching the Three.js mesh from the loader outside the designated area

Currently, I am immersed in a project that involves Three.js. The challenge I am facing is trying to access the mesh (gltf.scene) in the GLTF load from an external source. However, whenever I attempt to console.log outside of the loader, it shows up as undefined. Despite dedicating hours to unraveling this mystery, I have yet to find a solution. I suspect that this issue may be due to its asynchronous nature, but I cannot say for certain.

class mainCharacter {
  constructor(game) {
...
...
...
this.character;
this.loader = new GLTFLoader();
this.loader.load("./c.glb",(gltf)=>{
this.character= gltf.scene;
});
console.log(this.character);


}

I even experimented with using async functions without success.

class mainCharacter {
  constructor(game) {
...
...
...
this.character;
this.loadMain();
console.log(this.character);
})

async loadMain(){
    const loader = new GLTFLoader();
    this.character = await loader.loadAsync("./c.glb");
    this.character.scene.scale.set(13, 13, 13);
    this.scene.add(this.character.scene);
}

It appears that utilizing await before loadMain() and console.log(this.character) yields results. However, since the constructor function is not asynchronous, I cannot use await within it. If anyone has insights or suggestions, please lend me your assistance :'(

Thank you!

Answer №1

The ThreeJS documentation (available at this link) explains that the method loadAsync does not directly return the loaded mesh, but instead returns a Promise event.

.loadAsync ( url : String, onProgress : Function ) : Promise

Therefore, in order to handle the loaded content, you need to define an onLoad callback function as shown below:

this.mesh = await loader.loadAsync("./model.glb").then(function(data) {
  console.log(data); // Output: "Success"
});

Answer №2

Create another static function (similar to load demonstrated below) within your class and include this as an argument

class mainCharacter {
  constructor(game) {
    ...
    this.character;
    this.loader;
    mainCharacter.load(this);
    ...
  }
  static load(self) {
    self.loader = new GLTFLoader();
    self.loader.load(
      "./c.glb",
      (gltf) => self.character = gltf.scene
    );
  }
}

In arrow functions, the context of this refers to the owner of that function or the object in which the specific arrow function is defined. In this scenario, this within the arrow function does not point to the mainCharacter object because it is actually declared in and passed on to the loader.load() function. Refer to https://www.w3schools.com/js/js_arrow_function.asp for further information.

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

What is the best location to store common utility functions that will be utilized by various Vue.js components?

Typically, I create functions within the component that will use them. However, I am finding that I need to use a particular function in multiple components now. Currently, I would have to duplicate and paste the function into each component, which is not ...

Can a single camera be utilized for capturing two different scenes?

Hey there! I'm currently working on rendering two different scenes with a camera that moves in sync between the two. Here's what I'm trying to accomplish: I need to display two separate point clouds in two distinct scenes, but I want the ca ...

What is the best way to retrieve the previously chosen item from an array?

I have successfully implemented dynamic pill tabs with one minor issue remaining. The most crucial aspect is that when I remove a pill, I want it to return to the previously opened tab. I have provided a StackBlitz example without routes on this page: -> ...

Mastering the art of counting down using a forEach loop in JavaScript

Trying to iterate through a list of objects, I can't index it, but can use forEach. My issue is I need to start from the last object and go to the first, but unsure how to achieve that with the forEach function. If I used a for loop, it would be like ...

Are none of the page links clickable?

Currently, I am in the process of creating a portfolio website. This is my first attempt at coding HTML and CSS from scratch without the aid of a layout template. I've encountered an issue that has me stumped - the links within the container are not ...

Does using breakpoints in strict mode affect the outcome?

Here is the code snippet: 'use strict'; var foo=function(){ alert(this); } var bar = { baz:foo, }; var x = bar.baz; x();//1 After executing the code directly, everything works fine and it alerts undefined. However, when I insert a break ...

My custom function is not invoking the Firebase function createUserWithEmailAndPassword

The function createUserWithEmailAndPassword is not being triggered within the SignUpUser function when the onClick event occurs. However, it works when I use onClick={signUpUser(email,password)} import React from 'react'; import styled from &apo ...

I'm encountering an issue with fetching table data using AJAX, as I consistently receive an undefined value in Console.log every time I try to fetch req_id from the table. Can anyone help me

I am struggling to fetch the req_id from the table as it always shows undefined in Console.log(). Despite having a successful database connection and data availability in the table, I have attempted both GET and POST methods without success. My main goal i ...

Ensure that the elements within the container automatically adjust their height to fill the entirety of the

I am facing a challenge in getting the items within a container to occupy the space in the desired way. The main issue lies in the fact that flexbox and CSS grid are designed to adjust to changes in width rather than height, whereas I require the opposite ...

Having trouble running Jest tests with three objects in my Vite Vue TypeScript project

Here is a snippet of code that I am testing: import {Line} from "../src/modules/objs/line"; import {SceneWrapper} from "../src/modules/scene/sceneWrapper"; import * as THREE from "three"; import {Dr ...

Using an array of JSON objects to set up a Backbone.js bootstrap-initialized application

Trying to bootstrap a backbone collection by using an array of JSON objects has led to some unexpected errors. When attempting to call reset on the collection object, an error from Backbone is thrown - Uncaught TypeError: undefined is not a function. Inte ...

Discovering a particular element involves iterating through the results returned by the findElements method in JavaScript

I am attempting to locate and interact with a specific item by comparing text from a list of items. The element distinguished by .list_of_items is a ul that consists of a list of li>a elements. I am uncertain about how to transfer the determined elemen ...

"Bootstrap-Wizard: How to troubleshoot the onPrevious function not working when used with an

I have been incorporating a bootstrap wizard into one of my applications, and I have encountered an issue. When attempting to utilize the index position of the tabs to achieve a specific goal, I found that it only works with the next button and not with th ...

Solution for accessing the callee function in JavaScript slide down operation

While exploring a tutorial from CSS Tricks about animating section height, I came across a solution that I would like to implement in my Angular 2 application. Here is the function responsible for expanding sections in my app: expandSection(element) { / ...

What is the best way to place content in a single div without it being divided into several separate boxes

Here is my code snippet: <div class="col-md-9"> <div id="statbox"> {% for obj in product_type %} {% for obj1 in vastu %} <script type="text/javascript"&g ...

I am working with Vue.js 2.0 and attempting to send an event from a `child component`

I've been working with Vue.js 2.0 and I'm facing an issue trying to emit an event from a child component to the parent component, but unfortunately, it's not functioning as expected. Here is a glimpse of my code: child component: <temp ...

Tips for filling a Rails dropdown list using a JSON array

My Ant show page showcases detailed information about different types of ants. There are two drop downs on the page - one for environment: [indoor, outdoor], and another for diet: [sugar, fat, protein]. When a parameter is selected from each dropdown, it ...

Acquire the <li> element when it is clicked using vanilla JavaScript

Whenever a user enters a value in an input field, my function automatically adds a <li> element to a <ul>. Additionally, the function assigns the attribute ( onclick="doneToggle" ) to the created <li>. function createListElement() { ...

How can I show a loading screen while making a synchronous AJAX call in Chrome?

Is there any method to show a loading screen in Chrome while using async:false in an AJAX call? The use of setTimeout poses several challenges when making multiple synchronous AJAX calls within the setTimeout function. Additionally, the loading indicator ...

How can we translate HTML entities generated by json_encode into matching XML conventions?

As I embark on the journey of creating a Samsung TV App, I find myself working within a strict system that only allows me to use JS and HTML5. One of the challenges I face is the need to send a JSON request to my web server to retrieve data for the emulato ...