Stephan Häberle
Stephan Häberle

Reputation: 390

three.js get Object3D by custom property

I'm creating LineSegments objects like this:

const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3));

const edges = new THREE.EdgesGeometry(geometry);
const line = new THREE.LineSegments(edges2, new THREE.LineBasicMaterial({ color: 0xffffff }));
scene.add(line);

Then I've added custom properties to my lines:

line.prop1 = "hello";
line.prop2 = "world";

How can I get all Objects where prop1 for example is "hello"?

Upvotes: 2

Views: 1277

Answers (1)

Mugen87
Mugen87

Reputation: 31026

You can't use a built-in method for this use case. Object3D.getObjectByProperty() only works if an object has a unique property value. This function should do the trick:

function getObjectsByProperty( object, property, value, result = [] ) {

    // check the current object

    if ( object[ property ] === value ) result.push( object );
  
    // check children

    for ( let i = 0, l = object.children.length; i < l; i ++ ) {

        const child = object.children[ i ];

        getObjectsByProperty( child, property, value, result );

    }
   
  return result;

}

//

const objects = getObjectsByProperty( scene, 'prop1', 'hello' );

Upvotes: 2

Related Questions