What is causing the object, which is clearly defined (as shown in the callback to JSONLoader), to be interpreted as undefined

Why is the THREE.Mesh() object showing as undefined even though it was defined in a THREE.JSONLoader()? Here is the code snippet...

1: var player;
2: var playerCallback = function(geo, mats){
3:     player = new THREE.Mesh(geo, new THREE.MeshFaceMaterial(mats));
4:     console.log("Loaded Model: " + 'resources/models/Player.js');
5: }
6: JSONLoader.load('resources/models/Player.js', playerCallback);
7: player.position.set(0, 20, 20);
8: player.physics = false;
9: scene.add(player);

The issue arises at line "7" where player is reported as undefined. However, just before that, "Loaded Model: resources/models/Player.js" is displayed correctly.

Answer №1

The reason for this code modification is that it is crucial to execute it after the playerCallback block. The JSONLoader is responsible for loading the external file, which can take some time. However, while waiting for the file to load, the script continues its execution.

During the loading process of the external file, the script tries to access an undefined variable (player). To resolve this issue, it is essential to ensure that the program only accesses the global player variable after it has been defined.

To rectify the code, make the following adjustments:

var player;
var playerCallback = function(geo, mats){
    player = new THREE.Mesh(geo, new THREE.MeshFaceMaterial(mats));
    console.log("Model Loaded: " + 'resources/models/Player.js');

    executePlayerActions();
}

JSONLoader.load('resources/models/Player.js', playerCallback);

function executePlayerActions() {
    player.position.set(0, 20, 20);
    player.physics = false;
    scene.add(player);
}

The solution involves moving the player code into another function and calling it only after confirming that the player has been defined (after the external file has finished loading).

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

Transferring data from Node.js server to React client with axios communication

I have a project in the works that involves tracking chefs and their new recipes. I am developing a simple frontend application where users can input a chef's username, which will then be sent to the backend for scraping several cooking websites to re ...

Calculating the frequency of a variable within a nested object in an Angular application

After assigning data fetched from an API to a variable called todayData, I noticed that there is a nested object named meals within it, which contains a property called name. My goal is to determine the frequency of occurrences in the name property within ...

Load data asynchronously using a promise in select2

Is there a way to load options for select2 asynchronously without using ajax requests? I want to retrieve values from a promise object instead. Currently, my code loads data in the query function, but this means that it queries the data with every keystrok ...

Retrieving a specific Project ID from Asana Task API using Node.js and parsing the JSON response

Utilizing the Asana Task API, we have the capability to retrieve a task's associated projects along with their GID and Notes (description text). The main objective Our aim is to extract the GID of the project containing #websiteprojecttemplate in its ...

Checking the efficiency of Graphql API

Currently, I am in the process of optimizing key features within my Node.js API which incorporates GraphQL. This API serves as a proxy, receiving requests from various sources and forwarding them to multiple APIs based on the request. I am interested in ...

Tips for minimizing unnecessary rerenders in child components that rely on cached information from the parent component

check out the sandbox here Application maintains state to compute a memoized value, which is then passed as props to the Options. When a change occurs in the state triggered by a callback function in Option, it causes a rerender of the main Application, r ...

Upgrade button-group to dropdown on small screens using Bootstrap 4

I am currently developing a web application and incorporating Bootstrap 4 for certain components such as forms and tables. Within the design, I have included buttons grouped together to display various actions. Below is an example code snippet: <li ...

Dynamically transcluding multiple elements in Angular

Angular 1.5 introduces the option to multi-transclude. An interesting feature would be the ability to transclude a variable number of items into a directive and specify their names and positions at a later stage (for example, in the link/compile functions ...

Error in cloned selections with bootstrap-selectpicker showing one less item

When duplicating a bootstrap-select dropdown, the duplicate dropdown appears to be offsetting selections by 1. For example, if the second option is clicked, the first one is actually selected. Here is an illustration: If "New Castle" is clicked in the ...

Exploring ways in JavaScript to locate every occurrence of a string within segments of URLs embedded in HTML code

I have a large HTML file (~50MB) and I need to extract all instances of strings that are between two specific strings (which contain forward slashes) in URLs. var content = '<div><a href="https://sample.org/something/here/091209283/?para ...

Creating a basic bar graph using d3.js with an array of input data

In my dataset, I have an array of form data that includes items like 'Male', 'Female', 'Prefer Not To Say'. I want to create a simple bar chart generator using D3.js that can display the percentages or counts of each item in t ...

Determine the data type of an object's key

I have a XInterface defined as: export interface XInterface { foo: (() => Foo[]) | Foo[], bar: string, baz: number } When declaring an object using this interface, I want the type of foo to be Foo[], like so: const myObj: XInterface = { ...

Tips for retrieving the final element from a corrupt JSON string using JavaScript

I've encountered an issue with a nodejs speech recognition API that provides multiple texts in a JSON like structure which renders the data invalid and useless. { "text": "Play" } { "text": "Play astronaut" } ...

Can you tell me the title of this pointer?

When utilizing the drag function in the RC-tree, a specific cursor is displayed. I am interested in using this cursor in another dragzone on my website, but I am uncertain of its name. This same cursor also appears when dragging highlighted text into the b ...

The state of XMLHttpRequest always remains in a perpetual state of progress, never

I have come across an MVC Core application. One of the methods in this application currently has the following structure: public IActionResult Call(string call) { Response.ContentType = "text/plain"; return Ok(call); } In addi ...

Using Passport authentication callback rather than redirecting the user

passport.authenticate('local-register',{ successRedirect: '/login', failureRedirect: '/path_to_greatness', })(req, res, next); In the process of developing a stateless API, I have encountered l ...

What is the process for deleting certain code from a main component within a React webpage without altering the main component itself?

I have a main component named Layout.jsx that includes the essential elements for the website such as the navigation bar and meta tags. It also contains a Google tag to track analytics across the entire site. Now, I have a specific webpage for Google Ads w ...

Ways to determine if a script is currently running within Node.js环境

In my Node.js script, I am importing a separate script that I want to be compatible with various JavaScript engines. Specifically, I only want the line exports.x = y; to run if the code is being executed in a Node.js environment. How can I determine this ...

Interested in learning how to code games using JavaScript?

Hi everyone, I'm currently exploring the world of Javascript and have been tasked with completing a game for a class project. The game involves a truck that must catch falling kiwis while only being able to move left or right. A timer is set for two m ...

Leveraging custom properties in HTML elements with JavaScript

I am in the process of creating a straightforward battleships game that utilizes a 10x10 table as the playing grid. My goal is to make it easy to adjust the boat length and number of boats, which is why I'm attempting to store data within the HTML obj ...