scene.getObjectByName() undefined

Hello i have this curious problem where i have scene declared globally in my program, then from function called load() i load my models, then i have another function called createMesh() where i access to one of the childrens called “auto” in the scene, i dont know why because if i clg(scene) i found the “auto” node inside scene.children but when i do scene.getObjectByName(“auto”) returns me undefined. Black magic

here you get some code

```



let scene, etc etc

function initGraphs() {
scene = new three.Scene()

camera = new three.PerspectiveCamera(40, window.innerWidth/window.innerHeight,1 ,5000)

light = new three.AmbientLight(0x404040, 100)

renderer = new three.WebGLRenderer({antialias:true})

camera.position.z = 1000

scene.background = new three.Color(0xdddddd)

scene.add(light)

renderer.setSize(window.innerWidth, window.innerHeight)

document.body.appendChild(renderer.domElement)
}

function load(obj, name){

let loader = new GLTFLoader()

loader.load(obj, (gltf) => {

gltf.scene.name = name

scene.add(gltf.scene)

renderer.render(scene,camera)

})

}

Ammo().then(function (AmmoLib) {

Ammo = AmmoLib



start()

})

function start() {

initGraphs()

initPhysics()



load("auto/auto.gltf", "auto")

load("pista/pista.gltf")



createMesh()

}

function createMesh() {



console.log(scene.getObjectByName("auto")) //undefined why i dont know

}

```

Any response will be gratefully received!!

pd: i dont want to call scene.getobj… outside createMesh(), i need that there

You’re running into an async timing issue. GLTFLoader.load() is asynchronous, so when start() runs it calls load() and then immediately calls createMesh(). At that moment the model hasn’t finished loading yet, so the "auto" object hasn’t been added to the scene. That’s why scene.getObjectByName("auto") returns undefined.

If you check scene.children later you will see it because the loader callback already executed by then.

You need to call createMesh() after the model is loaded, or wait until loading finishes.

For example you could do it inside the loader callback:

function load(obj, name){

let loader = new GLTFLoader()

loader.load(obj, (gltf) => {

gltf.scene.name = name

scene.add(gltf.scene)

createMesh()

renderer.render(scene,camera)

})

}

or pass a callback:

function load(obj, name, onLoaded){

let loader = new GLTFLoader()

loader.load(obj, (gltf) => {

gltf.scene.name = name

scene.add(gltf.scene)

if(onLoaded) onLoaded()

})

}

load("auto/auto.gltf", "auto", createMesh)

Then when createMesh() runs the "auto" node will already exist in the scene and scene.getObjectByName("auto") will work.

So nothing magical here, just the loader finishing after your function runs.

1 Like