Agent Zebra
Agent Zebra

Reputation: 4550

Three.js - accessing a child object in a scene

I'm trying to access the child object sole in a scene. I am able to access the var sole inside the loader function using obj, but I need to access it from outside the loader function.

Here's the working code and here's the json model file.

I can access it from inside the loader, like this:

var loader = new THREE.ObjectLoader();  
loader.load("models/shoe4.json", function (obj) {
    scene.add (obj);
    scene.rotation.y = Math.PI/1;
    scene.position.y = -5;
    scene.position.z = -24;

    var sole = obj.getObjectByName( "sole", true );
    sole.position.y = -5;

});

But I need to do something like this:

var loader = new THREE.ObjectLoader();  
loader.load("models/shoe4.json", function (obj) {
    scene.add (obj);
    scene.rotation.y = Math.PI/1;
    scene.position.y = -5;
    scene.position.z = -24;     
});

var sole = obj.getObjectByName( "sole", true );
sole.position.y = -5;

Basically I need to put it it's own function for later use.

I also tried

var sole = scene.getObjectByName( "sole", true );
sole.position.y = -5;

Which gave me the error :

Uncaught TypeError: Cannot read property 'getObjectByName' of undefined

How do I access the object sole from anywhere? Simply declaring var obj, is not working.

Upvotes: 1

Views: 4345

Answers (1)

Lee Jenkins
Lee Jenkins

Reputation: 2470

First you declare sole outside the scope of the lambda function, like this:

var sole = null;
var loader = new THREE.ObjectLoader();  
loader.load("models/shoe4.json", function (obj) {
    scene.add (obj);
    scene.rotation.y = Math.PI/1;
    scene.position.y = -5;
    scene.position.z = -24;

    sole = obj.getObjectByName( "sole", true );
    sole.position.y = -5;

});

// this will FAIL because sole is undefined when this line of code executes
sole.position.x = 5;

Second, the program must not access sole until after the lambda function is actually executed. If you're not familiar with the asynchronous (or event-driven) programming model, then you should do a little reading about it:

http://code.tutsplus.com/tutorials/event-based-programming-what-async-has-over-sync--net-30027

https://msdn.microsoft.com/en-us/library/windows/apps/Hh700330.aspx

Upvotes: 4

Related Questions