MrGarretto
MrGarretto

Reputation: 282

Three.js color.setHex on all meshes in a group

I'm currently trying to setup a system to select objects in the scene by hovering/clicking on them. The scene contains object groups, which were created like so (I'm still a beginner in three.js, so this code is probably far from the optimal way to do it):

var obj = new THREE.Object3D();
// Put all segments of the model together into a single object
for (c = 0; c < seg.length; c++) {
    obj.add(seg[c]);
}
// Add object to object array and update the screen
objects[objects.length] = obj;
scene.add(objects[objects.length-1]);

The problem is that when I want to change the color of the meshes in the object groups after they are already in the scene, there is an error (color.setHex is undefined). The code that I tried to use to set the color looks like this:

for (j = 0; j < intersects[0].object.children.length; j++) {
    intersects[0].object.children[j].color.setHex(0x1A75FF);
}

Upvotes: 0

Views: 2879

Answers (2)

Mauricio Chiriboga
Mauricio Chiriboga

Reputation: 1

// create a container object
let groupObj = new THREE.Group(); 

// Put all segments of the model together into a single object
let obj1 = new THREE.Object3D();

// your code

groupObj.add(obj1); 

let obj2 = new THREE.Object3D();

  // your code

groupObj.add(obj2);

let obj3 = new THREE.Object3D();

// your code

groupObj.add(obj3); 

// add to scene
scene.add( groupObj ); 

// change the color of groupObj elements
for ( let i = 0; i < groupObj.children.length; i ++ ) {
   groupObj.children[i].material.color.setHex(0xffffff);
}

Upvotes: 0

MrGarretto
MrGarretto

Reputation: 282

I have figured it out thanks to gaitat:

without knowing the rest of the code you probably want intersects[0].object.children[j].material.color.setHex(0x1A75FF);

Now I just need to figure out how to make the raycaster work with the object groups, as that seems to be what's causing them to not be found now and placed in the intersects array.

Upvotes: 2

Related Questions