How to access imported gltf model

Hi everyone!

I’m beginner in Three.js, I’m trying to access some model imported by Cinema4D in gltf format.
I load it in my scene and I can see the model in canvas and all works untill here.

Now I need to access to this model so I can use all their properties.

This is my code:

const loader = new GLTFLoader();
loadModel("Lettino1", new Vector3(-50, -50, -500), new Vector3(0.2, 0.2, 0.2),"./models/sdraio.glb");

// !HELPERS
function loadModel(name, pos, scale, path) {
  loader.load(
    path,
    function (gltf) {
      let model;
      model = gltf.scene.children.find((child) => child.name === name);
      model.position.set(pos.x, pos.y, pos.z);
      model.scale.set(scale.x, scale.y, scale.z);
      scene.add(model);
    },
    undefined,
    function (error) {
      console.error(error);
    }
  );
}

I try to access to the model with this code

scene.children[1]

but it’s always undefined

Resume:
How can I access model after I imported it?

Thank you

Saving your models inside arrays/objects before adding them to the scene, is always a good move. myArray[0] = model. Because accessing them trough scene object may become quickly complicated
(if not fully loaded, or containing other types of objects, or structure changed)

Always execute the code when you 100% sure the model is loaded and you can access it.
I personally use a very primitive countdown (not fancy, but very flexible)

//declare how many models are loading outside function/loop
let countDown = numberOfModels

inside gtlf function at the end:

countDown -- 
if (countDown === 0) {
//execute code
}
1 Like

when? it isn’t shown in the code you posted. loadModel is async, so

loadModel(...)
scene.children[1]

will do nothing because the second line runs before it has finished loading.

the solution is to get familiar with async programing

async function loadModel(url) {
  return new Promise((res, rej) => loader.load(url, res, undefined, rej))
}

async function App() {
  const gltf = await loadModel('foo.glb')
  const model = gltf.scene.getObjectByName(name)
  if (model) {
    ...
    scene.add(model)
    console.log(scene.children[1]) // cannot possibly be undefined

and if you’re dealing with multiple models

const [foo, bar] = await Promise.all(['foo.glb', 'bar.glb'].map(loadModel))
console.log(foo.scene, bar.scene)

ps

model.position.set(pos.x, pos.y, pos.z) // ❌ 
model.position.copy(pos) // ✅

model.scale.set(scale.x, scale.y, scale.z) // ❌ 
model.scale.copy(scale) // ✅
model.scale.setScalar(scale) // ✅ better, if scale is a float

const model = gltf.scene.children.find((c) => c.name === name)  // ❌ 
const model = gltf.scene.getObjectByName(name) // ✅ this will deep search 
1 Like