OBJLoader.load
is a function that downloads and parses an OBJ file asynchronously. The time it takes for this process can vary, from instant to several seconds.
You mentioned calling init
followed immediately by displaypos
. Since these function calls happen sequentially, displaypos
will be executed right after init
finishes.
The sequence of events goes as follows:
- Initialize the global variable
pos
- Define the function
init
- Define the function
displaypos
- Call the function
init
- Assign
objloader
as a THREE.OBJLoader
- Set up the callback for
objLoader.load
- Invoke
objLoader.load
<-- Note: This is asynchronous and might require some time
init
finishes executing because the call to objloader.load
happens in sequence with a callback
- Call the function
displaypos
- Log
undefined
to the console
A few moments later...
- The callback for
objloader.load
gets triggered
- Add
object
to scene
- Assign a value to
pos
console.log
prints the correct value to the console
Therefore, your displaypos
call does not display the value because it hasn't been set yet.
You have the option to add your own callback to init
for the desired behavior or rewrite your code using Promise
+ async
/await
.
Callback approach
var pos;
function init(callback) {
var objLoader = new THREE.OBJLoader();
objLoader.load('objectfile.obj', function(object) {
scene.add(object);
pos = scene.children[5].children[0].geometry.attributes.position.getX(0);
console.log(pos); //This displays the vertex position value
callback(); // Points where execution exits
});
}
function displaypos() {
console.log(pos);
}
init(function(){
displaypos(); // now shows the correct value
});
// Alternatively: init(displaypos);
Promise + async/await method
var pos;
async function init() {
return new Promise(function(resolve){
var objLoader = new THREE.OBJLoader();
objLoader.load('objectfile.obj', function(object) {
scene.add(object);
pos = scene.children[5].children[0].geometry.attributes.position.getX(0);
console.log(pos); //This displays the vertex position value
resolve(); // Point where execution exits
});
});
}
function displaypos() {
console.log(pos);
}
(async function(){
await init();
displaypos(); // displays the correct value
})();