Select GLFT imported Objects By Name

Hi,

I’m trying to select a loaded object by name through a raycast. I thought I could simply load a .glft and define a name but it appears it’s only defined within the loader and not beyond the init(). I want to do it by name so i can specify html specific outputs depending on the object as i’ll have quite a few objects. I managed to make it work by selecting based on geometry.type i.e SphereGeometry or PlaneGeometry but can’t seem to figure out how to do it by the objects name as they’re always shown as undefined.

Hope this is clear enough and I’m not the 100th person to ask this question but i can’t seem to find a clear answer anywhere which works. I’m relatively new to threejs but have had a huge search around and can’t seem to find a clear answer to what i need so any help would be greatly appreciated!

Loader Example -
// Load GLFT Models

      var loader = new THREE.GLTFLoader(loadingManager);

      loader.load("/public/assets/models/suzan.gltf", function (Suzan) {

        Suzan.scene.position.set(0, 5, 5);

        scene.add(Suzan.scene);

        Suzan.name = 'Suzan';

      });

Raycast -

function onMouseDown(event) {

      event.preventDefault();

      mouse.x = (event.clientX / window.innerWidth) * 2 - 1;

      mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;

      raycaster.setFromCamera(mouse, camera);

      var intersects = raycaster.intersectObjects(scene.children, true);

      if (intersects.length > 0) {

        console.log(intersects[0].object.getObjectByName());

        switch (intersects[0].object.geometry.name) {

          case 'Suzan':

            console.log(model.name);

            openNav();

            break;

          default:

            break;

        }

      }

Raycast which works -

if (intersects.length > 0) {

        switch (intersects[0].object.geometry.type) {

          case 'PlaneGeometry':

            OpenVimeo();

            console.log('HIT PLANE');

            break;

          case 'SphereGeometry':

            openNav();

            console.log('HIT SPHERE');

            break;

            default:

            break;

        }

      }
1 Like

Solved it myself by using:

It takes the name you set in Blender and you can define it instead of defining on import - define before you import. Not sure if this is good or bad practice but it works for now!

if (intersects.length > 0) {
    var clickedName = intersects[0].object.name;
    console.log('You clicked: ' + clickedName); 
        switch (intersects[0].object.name) {
          case 'Suzanne':
            openNav();
            break;
            case 'Franky':
            OpenVimeo();
            break;
            default:
            break;
            
        }
      }
2 Likes