I am new to Three.JS, JavaScript, and programming in general with very minimal knowledge on using C# in Unity.
For now, I want to try and get custom 3D models rendering in the engine. I have successfully managed to render a rotating cube primitive but would like to try and load in a custom model. However, I am having trouble understanding how to implement the GLTFLoader.
Does anybody have a simple explanation or example on how to get a simple 3D model to render?
First of all you will need to reference GLTFLoader script after you referenced three.js.
Then you can create an instance of GLTFLoader, and then using it’s load method you can load the gltf or glb model from the given path. The load method takes minimum 2 parameters, first is the path of the model and the second is a callback that returns you the loaded model.
const loader = new THREE.GLTFLoader()
loader.load('./models/my_model.glb', (loadedModel) => {
scene.add(loadedModel.scene)
console.log('my model is loaded')
})
One confusing part may be the writing style of the callback method. This is a shorthand way to write anonymous functions. Alternatively you can write this code this way:
const loader = new THREE.GLTFLoader()
loader.load('./models/my_model.glb', callThisFuncWhenModelIsLoaded)
function callThisFuncWhenModelIsLoaded(loadedModel) {
scene.add(loaded_model.scene)
console.log('my model is loaded')
}