I had loaded an obj file using three.js I tried acquring its vertex 'X' position and save it in 'pos' inside the objloader function which is in the init() function. I want to use the variable's value in another function say displayposition() when I try
var pos;
function init() {
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
});
}
function displaypos() {
console.log(pos); //It doesn't display the vertex position value
}
How to make it global and make the variable value of 'pos' usable throughout the program..
OBJLoader.load
is an asynchronous function that downloads and parses the OBJ file. This may take no time at all, or it may take several seconds.
You say you are calling init
followed immediately by displaypos
. These function calls are sequential, so displaypos
will be called immediately after init
exits.
The order of operations here goes:
pos
init
functiondisplaypos
functioninit
objloader
as a THREE.OBJLoader
objLoader.load
objLoader.load
<-- This is asynchronous and may take some timeinit
exits because the call to objloader.load
was sequential with a callback displaypos
undefined
to the consoleA few seconds later...
objloader.load
is called
object
to scene
pos
console.log
prints the correct value to the console So your displaypos
call isn't printing the the value because there is no value to print... yet.
You can add your own callback to init
to make this work how you expect, or you can re-write your code to use Promise
+ async
/ await
.
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(); // The real exit point
});
}
function displaypos() {
console.log(pos);
}
init(function(){
displaypos(); // will now display the correct value
});
// alternately: init(displaypos);
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(); // the real exit point
});
});
}
function displaypos() {
console.log(pos);
}
(async function(){
await init();
displaypos(); // will display the correct value
})();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.