I have a question regarding my code. I'm currently working on making the loadCone()
function synchronous using async/await, but I'm facing some issues with it.
import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import conePath from "../../static/cone.glb";
import coneBaked from "../../static/coneBake.png";
import "regenerator-runtime/runtime";
export default class Cone {
constructor() {
this.cone;
const textureLoader = new THREE.TextureLoader();
const bakedTexture = textureLoader.load(coneBaked);
const bakedMaterial = new THREE.MeshBasicMaterial({
map: bakedTexture,
});
this.loadCone();
}
async loadCone() {
// GLTF loader
const gltfLoader = new GLTFLoader();
const cone = await gltfLoader.load(
conePath,
(gltf) => {
console.log("success");
console.log(gltf.scene);
this.cone = gltf.scene;
},
(progress) => {
// console.log("progress");
// console.log(progress);
},
(error) => {
console.log("error");
console.log(error);
}
);
}
getCone() {
return this.cone;
}
}
In another file, I am trying to add the cone like this:
const cone = new Cone();
this.scene.add(cone.getCone());
The issue I'm facing is that because getCone()
is synchronous, it gets executed before loadCone()
finishes loading the cone, resulting in getting undefined
instead of the actual cone object.
Any suggestions on how I can make my async loadCone()
function synchronous? I've tried using *.loadAsync()` but it didn't yield any different results.
Thank you in advance. So far, I haven't encountered any errors, except for the expected message saying "undefined is not an instance of THREE.Object3D".