title: three.js: Adding and replacing objects in scene
body: <p>I am trying out the following using three.js, where I have 2 shapes: “squares” and a “sphere”. </p>
  
  <p>Each object has a button associated with it. If the user clicks a button, the corresponding shape will be added to the scene however, there can only be 1 square and 1 sphere in a scene at any one time. </p>
  
  <p>If the user adds a new square, it should replace the old one. I seem to be having trouble achieving this though with my code below. Currently, I can successfully add the square and sphere objects however, when I click to add another square, the current square doesn’t get replaced. </p>
  
  <p>Please advise, thank you!</p>
  
  <pre><code>&lt;html&gt;
    &lt;head&gt;
      &lt;title&gt;My second three.js app&lt;/title&gt;
      &lt;style&gt;
        body { margin: 0; }
        canvas { width: 100%; height: 100% }
      &lt;/style&gt;
    &lt;/head&gt;
    &lt;body&gt;
      &lt;button id="button1"&gt;Square1&lt;/button&gt;
      &lt;button id="button2"&gt;Square2&lt;/button&gt;
      &lt;button id="button3"&gt;Sphere&lt;/button&gt;
      &lt;script src="js/three.js"&gt;&lt;/script&gt;
      &lt;script&gt;
    var scene = new THREE.Scene();
    var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
  
    var renderer = new THREE.WebGLRenderer();
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );
  
    loader.load( ‘square1.glb’, function ( geometry ) {
  
      geometry.scene.traverse( function ( node ) {
  
          if ( node.isMesh ){
              square = node;
              square.material.map.anisotropy = maxAnisotropy;
          }
  
      document.getElementById("button1").addEventListener("click", function(){
        scene.remove(square);
        scene.add(square);
  
      });
  
    });
  
    loader.load( ‘square2.glb’, function ( geometry ) {
  
      geometry.scene.traverse( function ( node ) {
  
        if ( node.isMesh ){
            square = node;
            square.material.map.anisotropy = maxAnisotropy;
        }
  
      document.getElementById("button2").addEventListener("click", function(){
        scene.remove(square);
        scene.add(square);
  
      });
  
    });
  
    loader.load( ‘sphere.glb’, function ( geometry ) {
  
      geometry.scene.traverse( function ( node ) {
  
        if ( node.isMesh ){
            sphere = node;
            sphere.material.map.anisotropy = maxAnisotropy;
        }
  
      document.getElementById("button3").addEventListener("click", function(){
  
      scene.add(sphere);
  
      });
  
    });
  
    var animate = function () {
      requestAnimationFrame( animate );
      renderer.render( scene, camera );
    };
  
    animate();
  &lt;/script&gt;
    &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>