Changing opacity of a object group

Hi,
I’m trying to change the opacity of a group of objects. I’ve created a codepen to show you what I’m trying to do. I’m trying to change the opacity of the group of meshes 'objGrp' via 'setOpacity' function. But it’s not working nor giving any error. Could you please help me out?
Thank you very much

1 Like

Hi,

You must loop through the group’s children to change the opacity of their material, with a recursive function. Something like this should do :

setOpacity( myGroup, 0.5 );
function setOpacity( obj, opacity ) {
  obj.children.forEach((child)=>{
    setOpacity( child, opacity );
  };
  if ( obj.material ) {
    obj.material.opacity = opacity ;
  };
};
2 Likes

Seems you call setOpacity() before any of your objects is loaded.

1 Like

I’ve added the function to the codepen, but it’s not working. :sweat:

I’ve called the function after adding the object group to the scene. Is that what you mean?

I mean, as you’re using THREE.LoadingManager(), you can call setOpacity() in the callback function, when all the models are loaded:

var manager = new THREE.LoadingManager();
manager.onLoad = function ( ) {

	setOpacity (objGrp, 0.5);

};

Having this, you don’t need the line with setOpacity(objGrp, 0.5) after adding the group to the scene.
Loading is an asynchronous operation. It means, that as you have it now, you try to set opacity to the objects that haven’t beed added yet to the group (as, obviously, they are loading at that moment, thus objGrp has no children).

https://codepen.io/prisoner849/pen/QevXqZ?editors=0010

2 Likes

Thanks for your input. My objective of creating a function is to control the opacity of the loaded meshes all at once with a dat.gui slider. Can this function used with dat.gui slider?

Ehm, why it can’t? :slight_smile:
I’ve updated the codepen: https://codepen.io/prisoner849/pen/QevXqZ?editors=0010

2 Likes

Thanks so much :slightly_smiling_face::smiley::beers::v:

@Brabbit_640
You’re welcome :slight_smile: :beers: