search

Home  >  Q&A  >  body text

Compare variable name and button ID to dynamically load content in ThreeJS

I'm using Three.js to load multiple 3D models and store them in an array behind the scenes. I have multiple buttons with unique IDs that add that specific model to the scene. Now I want to compare the button ID and variable name so that I can load only that specific model and remove any other models added to the scene. I wrote a for loop to loop through all the variables to compare to the ID of the button that was clicked, but I can't access just the variable name in order to compare it to the button ID.

The following is my code:

function modelShow() {

  let m;

  var models =  [mandi_0, maxi_0, mandi_1, maxi_1, mandi_2, maxi_2];

  for (m = 0; m < models.length; m++) {

    if(models[m].name == event.target.id){
      scene.add(models[m]);
    }
    else {
      scene.remove(models[m]);
    }
  }
}

let j;

for (j = 0; j < buttons.length; j++) {
   buttons[j].addEventListener('click', modelShow);
}

How to compare only the variable name with the button ID without comparing the content within the variable?

P粉301523298P粉301523298306 days ago424

reply all(1)I'll reply

  • P粉615886660

    P粉6158866602024-02-22 10:41:02

    Use objects with computed property names, not arrays.

    const modelsByName = {
      mandi_0,
      maxi_0,
      mandi_1,
      maxi_1,
      mandi_2,
      maxi_2,
    };

    Now you have an object like modelsByName["mandi_0"] === modelsByName.mandi_0 === mandi_0 and so on for other variables. But since you're not using an array, you can't iterate by index anymore, so change the loop.

    for ( let key in modelsByName ) {
      if ( modelsByName.hasOwnProperty( key ) && key === event.target.id ) {
        ...
      } else {
        ...
      }
    }

    reply
    0
  • Cancelreply